Unnamed: 0 int64 0 378k | id int64 49.9k 73.8M | title stringlengths 15 150 | question stringlengths 37 64.2k | answer stringlengths 37 44.1k | tags stringlengths 5 106 | score int64 -10 5.87k |
|---|---|---|---|---|---|---|
4,700 | 36,970,623 | PyAudio: when is it safe to modify the callback buffer? | <p>A typical PyAudio callback operating in output mode is:</p>
<pre><code>def callback(ignored, frame_count, time_info, status):
buffer = <fill and return a buffer with frame_count samples of data>
return (buffer, pyaudio.paContinue)
</code></pre>
<p>I haven't tried it, but I'm pretty sure that if I sta... | <p>Since the callback runs in a different thread, it's basically never safe to access your <code>buffer</code> from the main thread and you cannot know <em>immediately</em> when the callback is finished (at least not without blocking the callback, which you should try to avoid). However, you can cycle through a list of... | python|numpy|pyaudio | 0 |
4,701 | 37,014,715 | Efficiently comparing data across rows in a Pandas Dataframe | <p>I have a <code>CSV</code> file of monthly cell phone bills in no particular order that I read into a <code>Pandas</code> <code>Dataframe</code>. I'd like to add a column for each bill that shows how much it differed from the previous bill for the same account. This CSV is just a sub-set of my data. My code works fin... | <pre><code>df = pd.DataFrame({
'Account Number': {0: 4543, 1: 4543, 2: 4543, 3: 2322, 4: 2322, 5: 2322},
'Bill Amount': {0: 300.0, 1: 100.0, 2: 200.0, 3: 22.0, 4: 38.0, 5: 25.0},
'Bill Month': {
0: pd.Timestamp('2015-03-01 00:00:00'),
1: pd.Timestamp('2015-01-01 00:00:00'),
2: pd.Tim... | python|python-2.7|pandas | 1 |
4,702 | 54,969,646 | How does pytorch backprop through argmax? | <p>I'm building Kmeans in pytorch using gradient descent on centroid locations, instead of expectation-maximisation. Loss is the sum of square distances of each point to its nearest centroid. To identify which centroid is nearest to each point, I use argmin, which is not differentiable everywhere. However, pytorch is... | <p>As alvas noted in the comments, <code>argmax</code> is not differentiable. However, once you compute it and assign each datapoint to a cluster, the derivative of loss with respect to the location of these clusters is well-defined. This is what your algorithm does.</p>
<p>Why does it work? If you had only one cluste... | machine-learning|cluster-analysis|pytorch|k-means|backpropagation | 18 |
4,703 | 55,081,439 | Python, Splitting Multiple Strings in a Column | <p>Good afternoon, i am trying to split text in a column to a specfic format
here is my table below</p>
<pre><code>UserId Application
1 Grey Blue::Black Orange;White:Green
2 Yellow Purple::Orange Grey;Blue Pink::Red
</code></pre>
<p>I would like it to read the following:</p>
<pre><code>UserId Applicati... | <p>Maybe you can try using <code>extractall</code></p>
<pre><code>yourdf=df.set_index('UserId').Application.str.extractall(r'(\w+):').reset_index(level=0)
# You can adding rename(columns={0:'Application'})at the end
Out[87]:
UserId 0
match
0 1 Grey
1 1 White
0 ... | python|pandas|numpy|dataframe|text | 2 |
4,704 | 28,253,102 | Python 3: Multiply a vector by a matrix without NumPy | <p>I'm fairly new to Python and trying to create a function to multiply a vector by a matrix (of any column size).
e.g.:</p>
<pre><code>multiply([1,0,0,1,0,0], [[0,1],[1,1],[1,0],[1,0],[1,1],[0,1]])
[1, 1]
</code></pre>
<p>Here is my code:</p>
<pre><code>def multiply(v, G):
result = []
total = 0
for i i... | <p>The Numpythonic approach: (using <code>numpy.dot</code> in order to get the dot product of two matrices)</p>
<pre><code>In [1]: import numpy as np
In [3]: np.dot([1,0,0,1,0,0], [[0,1],[1,1],[1,0],[1,0],[1,1],[0,1]])
Out[3]: array([1, 1])
</code></pre>
<p>The Pythonic approach:</p>
<p>The length of your second <c... | python|python-3.x|numpy|matrix|vector | 10 |
4,705 | 34,935,329 | Iterate over a column in a dataframe matching each value with a value in another column in another dataframe | <p>I basically have two data frames. Let's say aa and bb. I want to look all the values in the first column of bb that are in the first column of aa and if they are I have to get column 2 of aa and add it to a new column in bb (if there is not much I'll put a 0). Let's see if looking at some code it makes more sense. I... | <p>Try this:</p>
<pre><code>res = pd.merge(aa, bb, left_on='a', right_on='c', how='inner', left_index=True)
bb['newcolumn']= res.reindex(range(len(aa))).fillna(0)['b']
print(bb)
</code></pre> | python|pandas | 0 |
4,706 | 34,972,297 | Fill in missing values in pandas dataframe using mean | <pre><code>datetime
2012-01-01 125.5010
2012-01-02 NaN
2012-01-03 125.5010
2013-01-04 NaN
2013-01-05 125.5010
2013-02-28 125.5010
2014-02-28 125.5010
2016-01-02 125.5010
2016-01-04 125.5010
2016-02-28 NaN
</code></pre>
<p>I would like to fill in the missig values in this dataframe by usi... | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> by <code>month</code> and <code>day</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow"><c... | python|pandas|dataframe|mean|missing-data | 1 |
4,707 | 35,277,725 | clojure working with scipy and numpy | <p>Is there any good way to call python from clojure as a means of doing data science with scipy, numpy, scikit-learn, etc.</p>
<p>I know about implementations of clojure which run on python instead of java, but this doeesn't work for me, as I also need to call java libraries in my project. I also know about Jython, b... | <p>Instead of trying to get Jython to play well with both Clojure and numpy/scipy, you can use <a href="http://docs.hylang.org/en/latest/" rel="noreferrer">Hy</a>. It is hosted on Python and it somewhat resembles Clojure.</p>
<p>If I really wanted to use numpy/scipy, I would write the backend in Python (or Hy), run it... | python|numpy|clojure|jython|data-science | 5 |
4,708 | 34,943,913 | pandas How to find all zeros in a column | <pre><code>import copy
head6= copy.deepcopy(df)
closed_day = head6[["DATEn","COUNTn"]]\
.groupby(head6['DATEn']).sum()
print closed_day.head(10)
</code></pre>
<p>Output:</p>
<pre><code> COUNTn
DATEn
06-29-13 11326823
06-30-13 5667746
07-01-13 8694140
07-02-13 7275701
0... | <p>After the groupby, COUNTn is converted into a Series, which doesn't have columns (it's just a single column). If you want to keep it as a dataframe, as your code is expecting, use <code>groupby(grouper, as_index=False)</code>.</p> | python|pandas | 1 |
4,709 | 31,098,228 | Solving system using linalg with constraints | <p>I want to solve some system in the form of matrices using <code>linalg</code>, but the resulting solutions should sum up to 1. For example, suppose there are 3 unknowns, x, y, z. After solving the system their values should sum up to 1, like .3, .5, .2. Can anyone please tell me how I can do that? </p>
<p>Currently... | <p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.solve.html" rel="noreferrer">Per the docs</a>, </p>
<blockquote>
<p><code>linalg.solve</code> is used to compute the "exact" solution, <code>x</code>, of the
well-determined, i.e., full rank, linear matrix equation <code>ax = b</code>.</p... | python|numpy|matrix|equation-solving | 14 |
4,710 | 67,301,172 | How to predict data from scikit-learn toy dataset | <p>I am studying machine learning and I am trying to analyze the scikit diabetes toy database. In this case, I want to change the default Bunch object to a pandas DataFrame object. I tried using the argument <em>as_frame=True</em> and it did actually change the object type to DataFrame.</p>
<p>So after that, I trained ... | <p>That is already a dataframe, you are getting error because you are plotting X_train with y_train and X_train has multiple columns.</p>
<p>but if you want your dataset in csv file you can use this code.</p>
<pre><code>X.to_csv('train_data.csv')
</code></pre>
<p>this will save that dataset into a csv file in your work... | python|pandas|matplotlib|machine-learning|scikit-learn | 0 |
4,711 | 34,859,391 | 2D NumPy array comparison in given range | <p>If I have a 2D array of numbers and I want to see if every value inside the array are inside another 2D array of by some range, how would you do it efficiently with NumPy?</p>
<pre><code>[[1,2,1],[2,3,2],[2,3,4],[1,2,3],[1,3,2]] is in range 1 with
[[1,2,1],[2,3,2],[2,3,4],[1,2,3],[1,3,2]] => TRUE
[[1,2,1],[2,3,... | <p>You can do this easily with numpy's vectorized arithmetic and <code>all</code>. For example:</p>
<pre><code>>>> a = np.array([[1,2,1],[2,3,2],[2,3,4],[1,2,3],[1,3,2]])
>>> b = np.array([[1,2,1],[2,3,2],[2,3,4],[1,2,3],[1,3,2]])
>>> abs(a-b)
array([[0, 0, 0],
[0, 0, 0],
[0, ... | python|arrays|numpy|comparison | 2 |
4,712 | 60,104,886 | Count the number of records based on a variable criteria Python | <p>I have a dataframe as follow: </p>
<pre><code>dashboard = pd.DataFrame({
'id':[1,1,1,1,1,2,2,3,3,4,4],
'level': [1,2,2.1,2.2,3,3.1,4,1.1,2,3,4],
'cost': [10,6,4,8,9,6,11,23,3,2,12],
'category': ['Original', 'Time', 'Money','Original','Original','Time','Original','Original','Time','Original','Original']
})
</cod... | <p>You can do it this way </p>
<pre><code>df2 = dashboard.groupby('id')['level'].last().astype(int).reset_index()
df2['cost'] = dashboard.groupby('id').apply(lambda x: x[x['level']>=(x['level'].tail(1)-0.9).sum()]['cost'].sum()-x['cost'].tail(1)).reset_index(drop=True)
df2['category'] = dashboard.groupby('id').appl... | python|pandas | 0 |
4,713 | 59,987,987 | ImportError and AttributeError for TensorFlow | <blockquote>
<p>Background</p>
</blockquote>
<p>I'm trying to work on a GAN neural network (I'm a beginner for both Python and Machine-Learning), and I need Tensorflow. </p>
<blockquote>
<p><strong>Problem</strong></p>
</blockquote>
<p>I have tried to use TensorFlow but can't install. I have read <a href="https:... | <p>I tried jumping through hoops on Windows, and did get Anaconda working, but not Tensorflow. I recommend running Ubuntu virtually, on WSL if you don't want to make any major changes to your machine. Ubuntu is pretty user friendly these days, even if you use it without any graphical shell enabled.<br>
Enable WSL, inst... | python|tensorflow|anaconda | 0 |
4,714 | 59,968,166 | Python tensorflow creating tfrecord with multiple array features | <p>I am following the TensorFlow <a href="https://www.tensorflow.org/tutorials/load_data/tfrecord" rel="nofollow noreferrer">docs</a> to generate a tf.record from three NumPy arrays, however, I am getting an error when trying to serialize the data. I want the resulting <code>tfrecord</code> to contain three features. <... | <p>Okay, I found time to have a closer look now. I noticed that the usage of <code>features_dataset</code> and <code>tf_serialize_example</code> comes from the tutorial on the tensorflow webppage. I don't know what the advantages of this method are and how to fix this.</p>
<p>But here's a workflow that should work fo... | python|tensorflow|tfrecord | 1 |
4,715 | 65,292,293 | Sorting a Pandas DataFrame by both column and row index at the same time | <p>I have a DataFrame, df, that I want to sort by both columns and rows at the same time.</p>
<pre><code>data = {'c2': ['4.0', '2.0', '1.0', '3.0'],
'c1': ['200', '100', '300', '400'],
'c3': ['aa', 'cc', 'dd', 'ee']}
df = pd.DataFrame(data)
df.index = ['d', 'b', 'c', 'a']
df
</code></pre>
<p>I have no pro... | <p>You can chain <code>sort_index</code>:</p>
<pre><code>df.sort_index().sort_index(axis=1)
</code></pre>
<p>Output:</p>
<pre><code> c1 c2 c3
a 400 3.0 ee
b 100 2.0 cc
c 300 1.0 dd
d 200 4.0 aa
</code></pre> | python|pandas | 1 |
4,716 | 49,880,927 | Vectorized pythonic way to get count of elements greater than current element | <p>I'd like to compare every entry in array b with its respective column to find how many entries (from that column) are larger than the reference. My code seems embarrassingly slow and I suspect it is due to for loops rather than vector operations.</p>
<p>Can we 'vectorize' the following code?</p>
<pre><code>import... | <p>It just needed a bit of deeper study to figure out that we could simply use <code>argsort()</code> indices along each column to get the count of greater than the current element at each iteration.</p>
<p><strong>Approach #1</strong></p>
<p>With that theory in mind, one solution would be simply using two <code>argsor... | python|performance|numpy|vectorization | 3 |
4,717 | 49,959,730 | Create a numpy.recarray from two lists python | <p>Is there a easy way to create a <code>numpy.recarray</code> from two lists. For instance, give the following lists:</p>
<pre><code>list1 = ["a","b","c"]
list2 = [1,2,3,4,5,6,7,8,9,10,11,12]
</code></pre>
<p>What I am trying to do is to get the following result:</p>
<pre><code>rec_array = np.rec.array([('a', 1), (... | <pre><code>In [73]: list1 = ["a","b","c"]
...: list2 = [1,2,3,4,5,6,7,8,9,10,11,12]
...:
In [74]: dt = [('string','|U5'),('int', '<i4')]
</code></pre>
<p>A simple pairing of elements:</p>
<pre><code>In [75]: [(i,j) for i, j in zip(list1,list2)]
Out[75]: [('a', 1), ('b', 2), ('c', 3)]
</code></pre>
<p>bre... | arrays|list|numpy | 1 |
4,718 | 63,865,722 | extract a list of tuples from pandas series stored as string | <p>I have a csv that I've read into pandas with the following format</p>
<pre><code>import pandas as pd
data = [['A', "[('a', 1), ('b', 2)]"], ['C', "[('c', 3), ('d', 4)]"]]
mydf = pd.DataFrame(data, columns = ['name', 'tupledat'])
</code></pre>
<p>how can I extract values from the second column... | <p>Check with <code>ast</code></p>
<pre><code>import ast
df.tupledat=df.tupledat.apply(ast.literal_eval)
df
Out[59]:
name tupledat
0 A [(a, 1), (b, 2)]
1 C [(c, 3), (d, 4)]
</code></pre> | python|pandas | 2 |
4,719 | 63,913,137 | Assign a category, according to range of the value as a new column, python | <p>I have a piece of R code that i am trying to figure out how to do in Python pandas.
It takes a column called INDUST_CODE and <strong>check its value to assign a category according to range of the value as a new column.</strong> May i ask how i can do something like that in python please?</p>
<pre><code> industry_in... | <p>You can use <code>pandas.cut</code> to organise this into bins in line with your example.</p>
<pre><code>df = pd.DataFrame([500, 1000, 1001, 1560, 1500, 2000, 2300, 7, 1499], columns=['INDUST_CODE'])
INDUST_CODE
0 500
1 1000
2 1001
3 1560
4 1500
5 2000
6 2... | python|r|pandas|range|categories | 2 |
4,720 | 63,839,881 | groupby aggregate does not work as expected for Pandas | <p>I need some help with aggregation and joining the dataframe groupby output.</p>
<p>Here is my dataframe:</p>
<pre><code> df = pd.DataFrame({
'Date': ['2020/08/18','2020/08/18', '2020/08/18', '2020/08/18', '2020/08/18', '2020/08/18', '2020/08/18'],
'Time':['Val3',60,30,'Val2',60,60,'Val2'],
'Val1': [0,... | <p>Groupby in pandas >= 0.25 will allow you to assign names to columns inside of it and do what you want in one go.</p>
<pre><code>df.groupby('Place').agg(Total_sum = ('Val1','sum'),
Factor = ('Val1', lambda x: round((x * 0.25).sum(),2)),
Val2_new = ('Val2', 'sum')).re... | python|pandas|pandas-groupby | 0 |
4,721 | 63,791,216 | Keras MaxPooling3D not allowed | <p>I'm trying to build a CNN and got stuck with MaxPooling3D layers not working. Both layers get an input shape of (1, 5, 32) and I'd like to max-pool over the depth using poolsize (1, 1, 32) so the output becomes of shape (1, 5, 1). However this throws the error:</p>
<pre><code>ValueError: Input 0 of layer max_poolin... | <p>your aim is to operate a 'pooling' on the the feature dimensionality... this is not the scope of the pooling layer... they operate pooling only on the spatial dimensionalities. you need something more simple</p>
<pre><code>n=5
inp_similarity = Input(shape=(n, n, 1))
conv11 = Conv2D(32, (n, 1))(inp_similarity)
conv... | python|tensorflow|keras|conv-neural-network|max-pooling | 2 |
4,722 | 64,070,776 | Write numpy array to buffer as jpeg | <p>I have a program which returns a stream of np.uin8 arrays. I would like to now broadcast these to a website being hosted by that computer.</p>
<p>I planned to do this by injecting the code in <a href="https://picamera.readthedocs.io/en/release-1.13/recipes2.html#web-streaming" rel="nofollow noreferrer">this</a> doc... | <p>OpenCV has functions to do this</p>
<p><code>retval, buf = cv.imencode(ext,img[, params])</code></p>
<p>lets you write an array to a memory buffer.</p>
<p>This <a href="https://github.com/jeffbass/imagezmq/blob/master/examples/pub_sub_broadcast.py" rel="nofollow noreferrer">example</a> here shows a basic implementat... | numpy|raspberry-pi|video-streaming|streaming|mjpeg | 0 |
4,723 | 63,832,786 | Effective way to use iterrows in pandas (another way) | <p>This is my first question on forum. Thanks for any help!</p>
<p>I wrote nested for loop based on df.iterrows () (sic.) and it takes a huuuuuge amount of time to perform. I need to assing value from one dataframe into another one by checking all the cells in described condition. Can you just help me to make it effect... | <p>Here is a way that goes from 2 for-loops to 1. I re-named a couple columns to cut line width.</p>
<p>First, create the data frames:</p>
<pre><code>import pandas as pd
d1 = {'geno_start' : [60, 1120, 1660],
'geno_end' : [90, 1150, 1690],
'original_subseq' : ['AAATGCCTGAACCTTGGAATTGGA',
... | python|pandas|multiprocessing|vectorization | 0 |
4,724 | 47,066,244 | Is it possible to get OpenCL on Windows Linux Subsystem? | <p>I'v been trying for the past day to get <strong>Tensorflow</strong> built with <strong>OpenCL</strong> on the Linux Subsystem. </p>
<p>I followed <a href="https://www.codeplay.com/portal/03-30-17-setting-up-tensorflow-with-opencl-using-sycl" rel="noreferrer">this guide</a>. But when typing <code>clinfo</code> it sa... | <p>With the launch of WSL2, CUDA programs are now supported in WSL (<a href="https://docs.nvidia.com/cuda/wsl-user-guide/index.html" rel="nofollow noreferrer">more information here</a>), however there is still no support for OpenCL as of this writing: <a href="https://github.com/microsoft/WSL/issues/6951" rel="nofollow... | linux|tensorflow|opencl|windows-subsystem-for-linux | 4 |
4,725 | 32,833,609 | How to circumvent the restriction on field names? | <p>If I define a recarray r with a field called data as follows</p>
<pre><code>import numpy
r = numpy.zeros( 1, numpy.dtype([('data', 'f8')]) ).view(numpy.recarray )
</code></pre>
<p>the data field will refer to some internal recarray buffer rather than a floating point number. Indeed, running</p>
<pre><code>r.data
... | <p>Here is the <code>getattribute</code> method for <code>recarray</code>. Python translates <code>obj.par1</code> to <code>obj.__getattribute__('par1')</code>. This would explain why the field name has to be a valid attribute name, when used in recarrays.</p>
<pre><code>def __getattribute__(self, attr):
try:
... | python-2.7|numpy|recarray | 3 |
4,726 | 32,789,991 | python, dimension subset of ndimage using indices stored in another image | <p>I have two images with the following dimensions, x, y, z:</p>
<p>img_a: 50, 50, 100</p>
<p>img_b: 50, 50</p>
<p>I'd like to reduce the z-dim of img_a from 100 to 1, grabbing just the value coincide with the indices stored in img_b, pixel by pixel, as indices vary throughout the image.</p>
<p>This should result i... | <p>Ok updated with a vectorized method.</p>
<p><a href="https://stackoverflow.com/questions/27277240/index-numpy-nd-array-along-last-dimension">Here</a> is a duplicate question but the solution currently doesn't work when the row and column dimensions are not the same size.</p>
<p>The code below has the method I adde... | python|numpy|indexing|ndimage | 0 |
4,727 | 38,626,435 | Tensorflow ValueError: No variables to save from | <p>I have written a tensorflow CNN and it is already trained. I wish to restore it to run it on a few samples but unfortunately its spitting out:</p>
<blockquote>
<p>ValueError: No variables to save</p>
</blockquote>
<p>My eval code can be found here:</p>
<pre class="lang-py prettyprint-override"><code>import tens... | <p>The <code>tf.train.Saver</code> must be created <em>after</em> the variables that you want to restore (or save). Additionally it must be created in the same graph as those variables.</p>
<p>Assuming that <code>Process.forward_propagation(…)</code> also creates the variables in your model, adding the saver creation ... | python|tensorflow|machine-learning | 27 |
4,728 | 38,543,850 | How to Display Custom Images in Tensorboard (e.g. Matplotlib Plots)? | <p>The <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/tensorboard/README.md#image-dashboard" rel="noreferrer">Image Dashboard</a> section of the Tensorboard ReadMe says:</p>
<blockquote>
<p>Since the image dashboard supports arbitrary pngs, you can use this to embed custom visualizations (e... | <p>It is quite easy to do if you have the image in a memory buffer. Below, I show an example, where a pyplot is saved to a buffer and then converted to a TF image representation which is then sent to an image summary.</p>
<pre><code>import io
import matplotlib.pyplot as plt
import tensorflow as tf
def gen_plot():
... | python|tensorflow|matplotlib|pytorch|tensorboard | 46 |
4,729 | 38,751,406 | No module named 'pandas' - Jupyter, Python3 Kernel, TensorFlow through Docker | <p>I have a Docker container running from tensrflow with Jupyter (Python 3 Kernel) image: erroneousboat/tensorflow-python3-jupyter</p>
<p>This works great and I can access the jupyter notebook from </p>
<p><code>http://DOCKER_IP:8888</code></p>
<p>My only issue is that pandas library is not installed. So, I tried to... | <p><code>pip install pandas</code> will install the latest version of pandas for you.</p>
<p>Based on your tags <code>python-3.x</code>, I assumed <code>pip</code> belongs to your Python3 version, if you have multiple python versions installed, make sure you have the correct pip.</p> | python-3.x|pandas|tensorflow|jupyter-notebook|docker-toolbox | 2 |
4,730 | 63,301,232 | how to use isin function in the IF condition in Python | <p>I am trying to use isin funtion in the if condtion within a function but it gives me an error</p>
<p>I have function <code>f</code> , and I am passing columns <code>A</code> from the dataframe <code>df</code> , and my if condition should check if A in <code>('IND','USA')</code> then return visited_countries else not... | <p>You need to use Series, not all DF, eg column A in DF so :
<code>if DF.A.isin(['IND','USA']).any():</code></p> | python|pandas|dataframe | 1 |
4,731 | 63,115,470 | replace the existing values to NAN in a given .csv file | <p>Hi there I'm a newbie in python learning through notebook, I have given iris dataset through .csv file and asked to replace one of the column values in some particular rows to NaN.I have tried "fillna" functions and "replace" functions but I'm not successful.Here is my code:</p>
<pre><code>import... | <p>Looks like the problem is, that you are not saving the resulting DataFrame from <code>.fillna()</code> or <code>.replace()</code>. By default, those methods return new DataFrame object. To fix this either save the result to a variable or use <code>inplace=True</code> argument in your <code>replace()</code> or <code>... | python|pandas|numpy | 2 |
4,732 | 63,167,919 | How can I check the image sizes while CNN? | <p>I'm trying to classify cat and dog in CNN with PyTorch.
While I made few layers and processing images, I found that final processed feature map size doesn't match with calculated size.
So I tried to check feature map size step by step in CNN process with print shape but it doesn't work.
I heard tensorflow enables ch... | <p>To do that you shouldn't use <code>nn.Sequential</code>. Just initialize your layers in <code>__init__()</code> and call them in the forward function. In the forward function you can print the shapes out. For example like this:</p>
<pre><code>class CNN(nn.Module):
def __init__(self):
super(CNN, self).__i... | python|pytorch|conv-neural-network | 0 |
4,733 | 67,893,599 | How to process a file located in Azure blob Storage using python with pandas read_fwf function | <p>I need to open and work on data coming in a text file with python.
The file will be stored in the Azure Blob storage or Azure file share.</p>
<p>However, my question is can I use the same modules and functions like os.chdir() and read_fwf() I was using in windows? The code I wanted to run:</p>
<pre><code>import pand... | <p>As far as I know, <code>os.chdir(path)</code> can only operate on local files. If you want to move files from storage to local, you can refer to the following code:</p>
<pre><code> connect_str = "<your-connection-string>"
blob_service_client = BlobServiceClient.from_connection_string(connect_s... | python|pandas|operating-system|azure-blob-storage|read-fwf | 0 |
4,734 | 67,608,501 | Looping through rows with condition using Pandas | <p>I am trying to iterate the rows with condition like in below dataframe by creating new column <strong>New_Course</strong>.</p>
<p>What I am looking for is when <strong>status= New and Status1=7</strong> then create new column <strong>New_COurse</strong> in below df and mark the sequence of course till the loop detec... | <p>Here is one way to do it:</p>
<pre><code># create the increasing new course
df['New_Course'] = (df.Status.eq('New') & df.status1.eq(7)).cumsum()
# set new course with Status=new and status1=0 as 0
df.loc[df.Status.eq('New') & df.status1.ne(7), 'New_Course'] = 0
# set other rows as NaN
df.loc[df.Status.ne('... | python|pandas | 1 |
4,735 | 67,978,203 | How to Find Time Since Last Game Played by a Team in Pandas | <p>I have a dataset that contains matchups of teams, and each team can be either team1 or team2 for any given matchup, I am looking to write a pandas function to create the following table which keeps track of how long it has been since the last game played by that team.</p>
<div class="s-table-container">
<table class... | <p>Starting from this <code>games</code> dataframe (with <code>game.date</code> a datetime columns), and a current date <code>curdate</code>:</p>
<pre><code>>>> games
team.id_team1 team.id_team2 game.date
0 3 23 2007-11-03
1 2 28 2007-11-03
2 1... | pandas|dataframe | 0 |
4,736 | 67,800,002 | TensorFlow 2.5 random set seed not working , Giving an Error | <pre><code>tf.random.set_seed(1234)
print(tf.random.uniform([1], seed=1)) # generates 'A1'
print(tf.random.uniform([1], seed=1)) # generates 'A2'
tf.random.set_seed(1234)
print(tf.random.uniform([1], seed=1)) # generates 'A1'
print(tf.random.uniform([1], seed=1)) # generates 'A2'
</code></pre>
<hr />
<blockquote>
<... | <blockquote>
<p>TypeError: 'int' object is not callable</p>
</blockquote>
<p>Generally you will get above error, if you have assigned some <code>integer</code> to <code>tf.random.set_seed</code> and tried to execute above code in the same session caused this issue.</p>
<pre><code>import tensorflow as tf
tf.random.set_... | python|tensorflow|google-colaboratory | 0 |
4,737 | 31,943,622 | drop a series of true false in pandas removes first two lines | <p>Handing the pandas.drop function a list of <code>True</code> and <code>False</code> statements drops the first two lines. Why? Is this a bug?</p>
<pre><code>df = pd.DataFrame({"foo":[1,2,3]})
df.drop([False, False, True])
foo
2 3
</code></pre>
<p>Also only giving it a list of <code>False</code> will just dro... | <h1>Explanation why this happens</h1>
<p>No, this is not a bug, it is just a side-effect of that <code>True</code> and <code>False</code> are equal to <code>1</code> and <code>0</code></p>
<p>This code:</p>
<pre><code>df = pd.DataFrame({"foo":[1,2,3]})
df.drop([False, False, True])
</code></pre>
<p>Is identic... | python|pandas | 4 |
4,738 | 41,488,676 | Python Data Frame: cumulative sum of column until condition is reached and return the index | <p>I am new in Python and am currently facing an issue I can't solve. I really hope you can help me out. English is not my native languge so I am sorry if I am not able to express myself properly.</p>
<p>Say I have a simple data frame with two columns:</p>
<pre><code>index Num_Albums Num_authors
0 10 ... | <p><strong><em>Opt - 1:</em></strong></p>
<p>You could compute the cumulative sum using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.cumsum.html" rel="noreferrer"><code>cumsum</code></a>. Then use <a href="https://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.isclose.html" r... | python|pandas|dataframe|sum | 7 |
4,739 | 41,645,365 | read_csv import large numbers | <p>A sample CSV file has contents like </p>
<pre><code>Afghanistan,AFG,8013233121.55065,8689883606.07776,8781610175.40574
</code></pre>
<p>When I import this with</p>
<pre><code>GDP = pd.read_csv('world_bank.csv', header=4, usecols=fields)
</code></pre>
<p>I get the numbers in scientific notation. </p>
<pre><code... | <p>Those numbers are floats. You are just seeing what is displayed.</p>
<p>Consider the following</p>
<pre><code>txt = """Afghanistan,AFG,8013233121.55065,8689883606.07776,8781610175.40574"""
GDP = pd.read_csv(StringIO(txt), header=None, converters={i:np.float128 for i in [2,3,4]})
print(GDP)
0 1 ... | python|pandas | 3 |
4,740 | 41,643,044 | What is the difference between tf.train.MonitoredTrainingSession and tf.train.Supervisor | <p>I'm wondering what is the difference between these 2 tensorflow object when used to train a neural networks ?</p> | <p>Supervisor is on the way to getting deprecated and new users are encouraged to use to tf.train.FooSession classes
(from <a href="https://github.com/tensorflow/tensorflow/issues/6604#issuecomment-270950324" rel="noreferrer">comment</a>)</p> | tensorflow | 8 |
4,741 | 61,579,248 | Using transformers-cli on Windows? | <p>I can't figure out how to use transformers-cli on Windows. I got it working on Google Colab, and am using it in the meantime.</p>
<p>[EDIT]</p>
<p>Here's the process that I'm going through, what I expect, and what is happening:</p>
<p><strong>I'm on a Windows System (brackets are the exact commands I'm typing int... | <p>All you have to do is to locate the script and launch it. It won't be added to the $PATH automatically. In my python interpreter installation on Windows 10 (not anaconda just python), it was installed in the <code>Scripts</code> folder of my python interpreter directory. You have to launch it with the python interpr... | huggingface-transformers | 3 |
4,742 | 68,526,277 | How to insert rows depending on previous row meeting conditions | <p>I have a simplified file (foo.csv),</p>
<p><strong>Contents of foo:</strong></p>
<pre><code>['MyNum', 'Cycle', 'Line', 'V1', 'V2', 'T1']
['1', 'C', '1', '6.7', '25.6', '90']
['3', 'A', '1', '5.8', '22.5', '89.9']
['3', 'A', '2', '5.8', '24.2', '90']
['3', 'A', '3', '5.8', '25.4', '90']
['5', 'B', '1', '6', '25.3', '... | <p>If input data are integers for <code>Line</code> column use custom lambda function with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>DataFrame.reindex</code></a> with <code>method='ffill'</code> for forward filling not existed value... | python|pandas|dataframe|numpy|csv | 2 |
4,743 | 68,556,648 | How to resolve ValueError: cannot reindex from a duplicate axis | <p><strong>Input</strong></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Client</th>
<th>First name</th>
<th>Last Name</th>
<th>Start Date</th>
<th>End Date</th>
<th>Amount</th>
<th>Invoice Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>XXX</td>
<td>John</td>
<td>Kennedy</td>
<td>15-01-2021</td... | <p>Start with some correction in your input Excel file, namely change <em>First name</em>
to <em>First Name</em> - with <strong>capital</strong> "N", just like in other columns.</p>
<p>Then, to read your Excel file, it is enough to run:</p>
<pre><code>df = pd.read_excel('Input.xlsx', parse_dates=['Start Date'... | python|pandas|dataframe|numpy|date | 1 |
4,744 | 36,627,362 | Converting a matrix into an image in Python | <p>I would like to save a numpy matrix as a .png image, but I cannot do so using the matplotlib since I would like to retain its original size (which apperently the matplotlib doesn't do so since it adds the scale and white background etc). Anyone knows how I can go around this problem using numpy or the PIL please? Th... | <p>Solved using scipy library</p>
<p>import scipy.misc</p>
<p>...(code)</p>
<p>scipy.misc.imsave(name,array,format)</p>
<p>or</p>
<p>scipy.misc.imsave('name.ext',array) where ext is the extension and hence determines the format at which the image will be stored.</p> | python|image|numpy|matrix|matplotlib | 1 |
4,745 | 65,797,708 | How to iterate over rows and index in a DataFrame in Pandas to filter bolean values | <p>I am working in a project to find anomalies though some stock market tickers, fishing abnormal volumes... I'm struggling to filters the True values(those pass in the 'filter').
The main objective is create a data frame with the tickers that passed on the ' stats filter'.</p>
<pre><code>import numpy as np
import pand... | <p>If you want to return the rows where at least one your tickers is <code>True</code>, this works:</p>
<pre><code>outlier[outlier.any(axis=1)]
</code></pre> | python|pandas|dataframe|yahoo-finance|outliers | 0 |
4,746 | 63,507,640 | Dividing values in a dataframe based on another value in dataframe | <p>I'm trying to create a column in a dataframe that is a result of dividing values based on another value in the dataframe.</p>
<p>So this means that i would like to divide the SCI value that has a corrosponding Temp value between 19.5 and 20.5 and equal chainage.</p>
<p>I created a small dataframe that could help sol... | <p>I think you need to break this up into a couple of steps.</p>
<ol>
<li>Compute your "base temperatures"</li>
<li>merge the base temps into the main dataframe</li>
<li>do the division</li>
<li>clean up the extra columns.</li>
</ol>
<p>That looks like this:</p>
<pre class="lang-py prettyprint-override"><code... | python|dataframe|pandas-groupby | 1 |
4,747 | 63,452,968 | ModuleNotFoundError: No module named 'dask.dataframe'; 'dask' is not a package | <p>For a current project, I am planning to merge two very large CSV files with Dask as an alternative to Pandas. I have installed Dask thorough <code>pip install "dask[dataframe]"</code>.</p>
<p>When running <code>import dask.dataframe as dd</code>, I am however receiving the feedback <code>ModuleNotFoundErro... | <p>As user John Gordon mentioned, the reason for the error notification is that a file within the same folder was named <code>dask.py</code>. Renaming the file solved the situation within seconds.</p>
<p>As a general rule/conclusion: is as advisable to not use .py file names that directly relate to Python modules.</p> | python|pandas|dask|dask-dataframe | 4 |
4,748 | 21,855,775 | numpy.i is missing. What is the recommended way to install it? | <p>I am writing a C++ library which can be called from both C++ and Python by using SWIG-Python interface. I would like to make a few functions in the library to return numpy array when they are used in Python.</p>
<p>The SWIG documentation [1] says that <code>numpy.i</code> located under <code>numpy/docs/swig</code> ... | <p>The safest option is probably just to bundle a copy of <code>numpy.i</code> with your project, as the file is not currently installed by Numpy itself.</p>
<p>The <code>numpy.i</code> file is written using Numpy's C-API, so the backward compatibility questions are the same as if you wrote the corresponding C code by... | python|numpy|swig | 4 |
4,749 | 21,498,474 | using numpy to randomly distribute DNA sequence reads over genomic features | <p>Hi I have written a script that randomly shuffles read sequences over the gene they were mapped to.
This is useful if you want to determine if a peak that you observe over your gene of interest is statistically significant. I use this code to calculate False Discovery Rates for peaks in my gene of interest.
Below th... | <p>Fancy indexing is a bit tricky, but still possible:</p>
<pre><code>for i in reads:
r = np.random.randint(-i,featurelength-1,iterations)
idx = np.clip(np.arange(i)[:,None]+r, 0, featurelength-1)
a[b,idx] += 1
</code></pre>
<p>To deconstruct this a bit, we're:</p>
<ol>
<li><p>Creating a simple index arr... | python|random|numpy|sequence | 0 |
4,750 | 30,039,988 | How to make a binary decomposition of pandas.Series column | <p>I want to decompose a <code>pandas.Series</code> into several other columns (number of column = number of values), save that factorization and use it with other <code>DataFrame</code> or <code>Series</code>. Something like <code>pandas.get_dummies</code> which will remember mapping and can handle <code>NaN</code>.</... | <p>I don't think there is a way to do this automatically:</p>
<pre><code>In [11]: res = df.pop("A").str.get_dummies() # Note: pop removes column A from df
In [12]: res.columns = res.columns.map(lambda x: "A_" + x)
In [13]: res
Out[13]:
A_a A_b A_c
0 1 0 0
1 0 1 0
2 1 0 0
3 0 0 ... | python|pandas|machine-learning|scikit-learn | 1 |
4,751 | 53,565,544 | Delimiting a region of a numpy matrix | <p>I have a 560x560 numpy matrix, which I want to convert to a 28x28 one. <br>
Therefore, I want to subdivide it into regions with size 16x16, calculate the mean of each such regions and put that value in a new matrix. <br> <br></p>
<p>Now I have:</p>
<pre><code>import numpy as np
oldMat = ... #... | <p>If you simply want to reshape your matrix from <code>2D --> 4D</code>, then you can use <code>np.reshape()</code>:</p>
<pre><code>import numpy as np
np.random.seed(0)
data = np.random.randint(0,5,size=(6,6))
</code></pre>
<p>Yields:</p>
<pre><code>[[4 0 3 3 3 1]
[3 2 4 0 0 4]
[2 1 0 1 1 0]
[1 4 3 0 3 0]
... | python|numpy|matrix | 0 |
4,752 | 53,464,487 | How to efficiently convert a subdictionary into matrix in python | <p>I have a dictionary like this:</p>
<pre><code>{'test2':{'hi':4,'bye':3}, 'religion.christian_20674': {'path': 1, 'religious': 1, 'hi':1}}
</code></pre>
<p>the value of this dictionary is itself a dictionary.</p>
<p>what my output should look like:</p>
<p><a href="https://i.stack.imgur.com/4EmsG.png" rel="nofollo... | <p>Using the pandas library you can easily turn your dictionary into a matrix.</p>
<p>Code:</p>
<pre><code>import pandas as pd
d = {'test2':{'hi':4,'bye':3}, 'religion.christian_20674': {'path': 1, 'religious': 1, 'hi':1}}
df = pd.DataFrame(d).T.fillna(0)
print(df)
</code></pre>
<p>Output:</p>
<pre><code> ... | python|arrays|numpy|dictionary|matrix | 2 |
4,753 | 53,684,017 | Replace specific words by user dictionary and others by 0 | <p>So I have a review dataset having reviews like </p>
<blockquote>
<p>Simply the best. I bought this last year. Still using. No problems
faced till date.Amazing battery life. Works fine in darkness or broad
daylight. Best gift for any book lover.</p>
</blockquote>
<p>(This is from the original dataset, I have ... | <p>First dont use <code>dict</code> as variable name, because builtins (python reserved word), then use <code>list comprehension</code> with <code>get</code> for replace not matched values to <code>0</code>.</p>
<p><strong>Notice</strong>:</p>
<p><em>If data are like <code>date.Amazing</code> - no space after punctua... | python|python-3.x|pandas|dictionary|dataframe | 1 |
4,754 | 53,643,746 | Create Dynamic Columns with Calculation | <p>I have a dataframe called prices, with historical stocks prices for the following companies:</p>
<p><em>['APPLE', 'AMAZON', 'GOOGLE']</em></p>
<p>So far on, with the help of a friendly user, I was able to create a dataframe for each of this periods with the following code:</p>
<pre><code>import pandas as pd
impor... | <p>IIUC, try this:</p>
<pre><code>def create_cols(df,num_dates):
for col in list(df)[1:]:
df['{}%'.format(col)] = - ((df['{}'.format(col)].shift(num_dates) - df['{}'.format(col)]) / df['{}'.format(col)].shift(num_dates)).shift(- num_dates)
return df
create_cols(prices,251)
</code></pre>
<p>you only w... | python-3.x|pandas|dataframe|dynamic-columns | 1 |
4,755 | 20,255,779 | What is best way to find first half of True's in boolean numpy array? | <p>Here is the problem:</p>
<p>Take a numpy boolean array:</p>
<pre><code>a = np.array([False, False, True, True, True, False, True, False])
</code></pre>
<p>Which I am using as indexes to panda dataframe. But I need to create 2 new arrays where they each have half the True's as the original array. Note the exampl... | <p>First find true indices</p>
<pre><code>inds = np.where(a)[0]
cutoff = inds[inds.shape[0]//2]
</code></pre>
<p>Set values equivalent before and after cutoff:</p>
<pre><code>b = np.zeros(a.shape,dtype=bool)
c = np.zeros(a.shape,dtype=bool)
c[cutoff:] = a[cutoff:]
b[:cutoff] = a[:cutoff]
</code></pre>
<p>Results:<... | python|arrays|numpy|pandas | 3 |
4,756 | 71,938,456 | How to use pandas concatenate | <p><a href="https://i.stack.imgur.com/C4wzJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C4wzJ.png" alt="enter image description here" /></a></p>
<p>Hi im running a program and I am being warned that the append method for pandas is being depreciated. How would I use concatenate in the following pi... | <pre><code>tweet = pd.Series({
'user_name': tweet.user.name,
'user_location': tweet.user.location,
'user_description': tweet.user.description,
'user_verified': tweet.user.verified,
'date': str(tweet.created_at),
'text': text,
'hashtags': [hashtags if hashtags else None],
'source': tweet.source})... | python|pandas | 2 |
4,757 | 22,048,341 | Importing Module(PyCogent) with Python | <p>I'm having trouble installing the Pycogent 1.5.3 module on Python. </p>
<ol>
<li>I Downloaded it(PyCogent-1.5.3.tgz) and then unzipped it with 7-zip.</li>
<li>I then open the cmd(windows), and go to the Pycogent directory. Then I try to set it up with "python setup.py install"</li>
<li>First error i had to deal wit... | <p>PyCogent does not work on windows unless you have a Linux virtual machine installed.</p>
<p>Taken from Pycogent's installation guide (<a href="http://pycogent.org/install.html" rel="nofollow noreferrer">here</a>):</p>
<p><img src="https://i.stack.imgur.com/EMJS9.png" alt="enter image description here"></p>
<p>Let... | python|windows|numpy|module | 0 |
4,758 | 4,623,800 | Is there support for sparse matrices in Python? | <p>Is there support for sparse matrices in python?</p>
<p>Possibly in numpy or in scipy?</p> | <p><strong>Yes.</strong></p>
<p>SciPi provides <a href="http://docs.scipy.org/doc/scipy/reference/sparse.html" rel="noreferrer">scipy.sparse</a>, a "2-D sparse matrix package for numeric data".</p>
<blockquote>
<p>There are seven available sparse matrix types:</p>
<ol>
<li>csc_matrix: Compressed Sparse Col... | python|numpy|scipy|sparse-matrix | 41 |
4,759 | 55,569,369 | Is there an pandas function to count element occurring after specific words? | <pre><code>df
['ch*', 'co*', 'DePe*', 'DePe*', 'DePe*', 'pm*', 'tpm*', 'lep*']
['ch*', 'co*', 'DePe*', 'DePe*', 'DePe*', 'am*', 'te*', 'qe*','te*']
['ch*', 'co*', 'DePe*', 'ch*', 'DePe*', 'DePe*', 'tpm*', 'lep*']
['ch*', 'DePe*', 'eeae*', 'ps*', 'er*']
Name: df, Length: 4, dtype: object
</code></pre>
<p>i need to coun... | <p>Use <code>apply</code> with lambda function and <code>index</code> of reversed <code>lists</code>, it working nice, because lists are 0 based indexed in python:</p>
<pre><code>df['count'] = df['A'].apply(lambda x: x[::-1].index('DePe*'))
print (df)
A count
0 [c... | python|pandas | 2 |
4,760 | 55,289,901 | Drop columns with no header on csv import with pandas | <p>Here is a sample csv:</p>
<pre><code>| Header A | | Unnamed: 1 | Header D |
|-----------|------|------------|-----------|
| a1 | b1 | c1 | d1 |
| a2 | b2 | c2 | d2 |
</code></pre>
<p>If I import it with <code>pandas.read_csv</code>, it turns into this:</p>
<p... | <p>The only way I can think of is to "peek" at the headers beforehand and get the indices of non-empty headers. Then it's not a case of dropping them, but not including them in the original df.</p>
<pre><code>import csv
import pandas as pd
with open('test.csv') as infile:
reader = csv.reader(infile)
headers ... | python|pandas|csv | 2 |
4,761 | 55,361,055 | Why can't I use a variable in an for x in df.itertuples loop created prior to that loop? | <p>This is probably a basic Pandas question but I can't figure it out?</p>
<p>I have this loop : </p>
<pre><code>n=0
for lum in lum_df.itertuples():
print(lum.X)
print(lum.Y)
lum_x = float(lum.X)
lum_y = float(lum.Y)
for point in street_df.itertuples():
print(point.X)
print(point.Y... | <pre><code>import pandas as pd
lum_df = pd.DataFrame({'X': [1, 2, 3, 4], 'Y': [3, 4, 5, 6]})
street_df = pd.DataFrame({'X': [5, 6, 7, 8], 'Y': [9, 10, 11, 12]})
for ix, lum in lum_df.iterrows():
print(float(lum.X))
print(float(lum.Y))
for ix, point in street_df.iterrows():
print(point.X)
p... | python|pandas|for-loop | 0 |
4,762 | 55,470,962 | numpy ndarray inside array using index | <p>I have a <code>numpy.ndarray</code> - <code>a</code></p>
<p>and <code>a[0]</code> gives me:</p>
<p><code>array([0., 0., 0., ..., 0., 0., 0.])</code></p>
<p>also <code>a[0:1]</code> gives: </p>
<p><code>array([[0., 0., 0., ..., 0., 0., 0.]])</code></p>
<p>How can I make <code>a[0]</code> to the format <code>arra... | <p>In case you want to reshape the array, so that every element of the first axis (every row) is an array of shape (1,m), instead of just (m,) you could do the following:</p>
<pre><code>a = a[:,np.newaxis,:]
</code></pre>
<p>This way the (n,m) array is transformed into shape (n,1,m) and getting the first row with <co... | python|python-3.x|numpy | 0 |
4,763 | 9,718,731 | Matlab -> scipy ode (complex) function translation | <p>I'm learning python, numpy and scipy.
I'm wonder if it is possible translate this kind of functions in matlab to python:</p>
<pre><code>function [tT, u ] = SSolve5TH(n, t, t0,tf,u_env,utop_init, utop_final,ubottom,te_idx)
options = [];
[tT,u] = ode23s(@SS,t,u_env,options,@B);
function y = B(x)
y = zeros(n,1);
... | <p>Yes, it's possible. Along these lines:</p>
<p><a href="http://scipy-central.org/item/13/2/integrating-an-initial-value-problem-multiple-odes" rel="nofollow noreferrer">http://scipy-central.org/item/13/2/integrating-an-initial-value-problem-multiple-odes</a></p>
<p>Just replace 'vode' with 'zvode'. Or:</p>
<p><a h... | python|matlab|numpy|scipy|ode | 1 |
4,764 | 7,140,560 | numpy sum along axis | <p>Is there a numpy function to sum an array <em>along</em> (not over) a given axis? By along an axis, I mean something equivalent to:</p>
<pre><code>[x.sum() for x in arr.swapaxes(0,i)].
</code></pre>
<p>to sum <em>along</em> axis i.</p>
<p>For example, a case where numpy.sum will not work directly:</p>
<pre><code... | <p>You can just pass a tuple with the axes that you want to sum over, and leave out the one that you want to 'sum along':</p>
<pre><code>>> a.sum(axis=(1,2))
array([ 6, 22, 38])
</code></pre> | numpy|sum|axis | 5 |
4,765 | 56,507,181 | How to change the date format while writing it to excel file using openpyxl | <p>I want to convert the date format from <code>dd-mm-yy</code> to <code>mm-yy</code> while writing it into excel file. I tried all the methods but to no success. I am trying to copy data from one excel file and paste it into another. But the date messes up everything.</p>
<p>This is my original Document. From where t... | <p>If you have a variable with all the content you want to write, just use the <code>datetime_format</code> and NOT the <code>date_format</code>.</p>
<p>For instance, I am deleting a sheet called <code>ValorLiq</code> and then rewriting it. I have the content I want to write in <code>myFILE</code>.
The commands are:</p... | python|python-3.x|pandas|openpyxl | 2 |
4,766 | 56,749,460 | How do i display dictionaries on new tkinter window | <p>I'm working on excel file to show the data on new tkinter window.</p>
<p>Here is the excel data i converted to dict:</p>
<pre><code>{'Country': {0: 'Japan', 1: 'China', 2: 'USA', 3: 'Russia', 4: 'Japan',
5: 'Japan', 6: 'China'}, 'Port': {0: 'Yokohama', 1: 'Ningbo', 2:
'Baltimore', 3: 'Moscow', 4: 'Tokyo', 5: 'To... | <p>Here convert to list with dictioanry is not necessary, use:</p>
<pre><code>df = pd.DataFrame(a)
print (df)
Country Port incoterm Capacity Date Oct Nov Dec $ value \
0 Japan Yokohama FOB 40ton NaN 400 500 100 2650.6
1 China Ningbo DAT 40ton NaN 500 200 200 265... | python|python-3.x|pandas|tkinter | 1 |
4,767 | 56,643,625 | how to efficiently divide a large image to several parts and rotate them? | <p>Given a big picture the following takes a lot of time:</p>
<p><strong>1</strong>
cut image to 4 evenly shaped images (divide the image one time in the middle horizontally, and divide the image one time vertically):</p>
<p><a href="https://i.stack.imgur.com/soAVC.png" rel="nofollow noreferrer"><img src="https://i.s... | <p>We could simply get the views for virtually free runtime with array-slicing, like so -</p>
<pre><code>B = image_np[-1:int(size / 2)-1:-1, ::-1, :]
C = image_np[::-1, :int(size / 2),:].swapaxes(0,1)
D = image_np[:, -1:int(size / 2)-1:-1, :].swapaxes(0,1)
</code></pre>
<p><code>image_A = image_np[: int(size / 2), :,... | python|image|numpy | 1 |
4,768 | 26,337,189 | python: multiply two columns of nd-arrays to get the vector of same dimensions? | <p>I have the following code:</p>
<pre><code> x = np.random.randint(0,10,size=(10,2))
y = np.random.randint(0,10,size=(10,2))
</code></pre>
<p>x and y are <code>10 x 2</code> matrix. Now I want to multiply second column of x and y. I did
<code>z = x[:,1] * y[:,1].</code> I got the result but z is <code>1 x 10</code>... | <p>Instead of getting the exact column use slicing, that way shape will be preserved:</p>
<pre><code>>>> x = np.random.randint(0, 10, size=(10, 2))
>>> y = np.random.randint(0, 10, size=(10, 2))
>>> x[:,1:2] * y[:,1:2]
array([[36],
[ 0],
[ 0],
[45],
[ 5],
[... | python|arrays|numpy | 6 |
4,769 | 66,913,089 | Overloading "==" operator for numpy arrays | <p>I am defining a function in Python that needs to check</p>
<pre><code>if a==b:
do.stuff()
</code></pre>
<p>In principle, <code>a</code> and <code>b</code> could be numpy arrays or integers, and I would like my implementation to be robust against this. However, to check equality for a numpy array, one needs to appe... | <p>how about this that works for both arrays and integers(numbers):</p>
<pre><code>if np.array_equal(a,b):
do.stuff()
</code></pre> | python|numpy|operator-overloading | 1 |
4,770 | 66,806,974 | Executing .py file from Command Prompt raises "ImportError: no module named geopandas"- Script works in Spyder (using anaconda) | <p>I have a python script that accomplishes a few small tasks:</p>
<ol>
<li>Create new directory structure</li>
<li>Download a .zip file from a URL and unzip contents</li>
<li>Clean up the data</li>
<li>Export data as a .csv</li>
</ol>
<p>The full .py file runs successfully giving desired output when in Spyder, but whe... | <p>I figured out I wasn't calling python in command prompt before executing the python file.
The proper command is <code>python modulename.py</code> instead of <code>modulename.py</code> if you want to execute a .py file from the command prompt. Yikes. Let this be a lesson for other python novices.</p> | python|anaconda|command-prompt|geopandas | 1 |
4,771 | 47,224,930 | Unable to import pandas on CentOS machine | <p>While importing pandas I am getting below error:</p>
<pre><code>>>> import pandas as pd
**RuntimeError: module compiled against API version 6 but this version of numpy is 4**
numpy.core.multiarray failed to import
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "... | <p>Well the module's answer to your import request seems to be pretty self-explaining. Did you try a </p>
<pre><code>yum update numpy
</code></pre>
<p>If that doesn't fix your problem (I don't know what repos your centos distro uses) you could always try the pip approach</p>
<pre><code>pip install -U numpy
</code><... | python|linux|pandas|centos6 | 0 |
4,772 | 47,240,308 | Differences between numpy.random.rand vs numpy.random.randn in Python | <p>What are the differences between <code>numpy.random.rand</code> and <code>numpy.random.randn</code>?</p>
<p>From the documentation, I know the only difference between them is the probabilistic distribution each number is drawn from, but the overall structure (dimension) and data type used (float) is the same. I have... | <p>First, as you see from the documentation <code>numpy.random.randn</code> generates samples from the normal distribution, while <code>numpy.random.rand</code> from a uniform distribution (in the range [0,1)).</p>
<p>Second, why did the uniform distribution not work? The main reason is the activation function, especia... | python|numpy|neural-network|numpy-random | 129 |
4,773 | 47,419,345 | Save rows of a bidimensional numpy array in another array | <p>I have a bidimensional np array V (100000x50). I want to create a new array V_tgt in which I keep just certain rows of V, so the dimension will be (ix50). It may be easy to do it but I tried different things and it seems to save just the first of the 50 elements. My code is the following:</p>
<pre><code>V_tgt = np.... | <p>From your comments I assume that you have some kind of list of target indices (in my example <code>tgt_idx1</code> and <code>tgt_idx2</code>)that tells you which elements to take from V. You could do something like this:</p>
<pre><code>import numpy as np
V = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
tgt_... | python|arrays|numpy | 0 |
4,774 | 11,248,812 | How to plot data from multiple two column text files with legends in Matplotlib? | <p>How do I open multiple text files from different directories and plot them on a single graph with legends?</p> | <p>This is relatively simple if you use pylab (included with matplotlib) instead of matplotlib directly. Start off with a list of filenames and legend names, like [ ('name of file 1', 'label 1'), ('name of file 2', 'label 2'), ...]. Then you can use something like the following:</p>
<pre><code>import pylab
datalist =... | python|numpy|matplotlib | 30 |
4,775 | 68,418,216 | Dropping number of columns (ending with same letter) from pandas dataframe | <p><a href="https://i.stack.imgur.com/RBMaZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RBMaZ.png" alt="enter image description here" /></a></p>
<p>I want to drop all columns ending with "T". I used for loop which works. I want to know is there any better way. My code-</p>
<pre><code>fo... | <p>Try:</p>
<pre><code>df=df.drop(df.filter(regex='T$').columns,axis=1)
</code></pre>
<p>OR</p>
<pre><code>df=df.loc[:,~df.columns.str.endswith('T')]
</code></pre>
<p>OR</p>
<pre><code>df=df.loc[:,~(df.columns.str[-1]=='T')]
</code></pre> | python|pandas | 0 |
4,776 | 68,087,213 | Pandas Read Excel, or faster method | <p>I didn't find any related thread.</p>
<p>I have a not so big Excel file (100 MB), but quite large (ie 930 columns for 35k rows), and that's my problem.
Excel read this file in a second, but pandas took at least 10-20 minutes on my computer.
I tried the following:</p>
<ul>
<li>not infering type, by giving dtype param... | <p>Consider an ODBC connection to Excel workbook to query worksheet like a database table with <code>pandas.read_sql</code>. Below ODBC driver installs with most Windows MS Office installations. SQL query retrieves one column, <code>H11</code>, and first 200 rows of worksheet named <code>mySheet</code>.</p>
<pre class=... | python|excel|pandas | 2 |
4,777 | 59,376,213 | Expected performance of training tf.keras.Sequential model with model.fit, model.fit_generator and model.train_on_batch | <p>I am using tensorflow to train a 1D CNN to detect specific events from sensor data. While the data with tens of millions samples easily fits to the ram in the form of an 1D float array, it obviously takes a huge amount of memory to store the data as a N x inputDim array that can be passed to model.fit for training. ... | <p><strong>model.fit</strong> - suitable if you load the data as numpy-array and train without augmentation.</p>
<p><strong>model.fit_generator</strong> - if your dataset is too big to fit in the memory or\and you want to apply augmentation on the fly. </p>
<p><strong>model.train_on_batch</strong> - less common, usua... | python-3.x|tensorflow2.0 | 0 |
4,778 | 59,350,190 | Cannot convert Pandas Dataframe columns to float | <p>I am using Pandas to read a CSV file containing several columns that must be converted to floats:</p>
<pre><code> df = pd.read_csv(r'dataset.csv', low_memory=False, sep = ',')
df.head(2)
Coal Flow 01 Air Flow 01 Outlet Temp 01 Inlet Temp 01 Bowl DP 01 Current 01 Vibration 01
0 51.454407 ... | <p>Why not just use <code>astype</code>:</p>
<pre><code>df = pd.read_csv(r'dataset.csv', low_memory=False, sep = ',')
df[features] = df[features].apply(lambda x: x.apply(lambda x: x[0]).astype(float))
</code></pre> | python|pandas|numpy|pytorch | 1 |
4,779 | 59,473,894 | Using Tensorflows Universal Sentence Encoder in Node.js? | <p>I'm using tensorflow js in node and trying to encode my inputs.</p>
<pre><code>const tf = require('@tensorflow/tfjs-node');
const argparse = require('argparse');
const use = require('@tensorflow-models/universal-sentence-encoder');
</code></pre>
<p>These are imports, the suggested import statement (ES6) isn't perm... | <p><code>load</code> returns a promise that resolve to the model</p>
<pre><code>use.load().then(model => {
// use the model here
let embeddings = model.embed(sentences);
console.log(embeddings.shape);
})
</code></pre>
<p>If you would rather use <code>await</code>, the <code>load</code> method needs to be in... | javascript|node.js|tensorflow|tensorflow.js|encoder | 3 |
4,780 | 59,110,612 | Pandas groupby mode every n rows | <p>I have a pandas df that I am trying to groupby every 3 rows and get the mode. How can I do this?</p>
<p>Example: </p>
<pre><code>time a b
0 0.5 -2.0
1 0.5 -2.0
2 ... | <p>You can use <code>groupby</code> and <code>mode</code>:</p>
<pre><code>df.groupby(np.arange(len(df)) // 3).agg(lambda x: x.mode().to_numpy()[-1])
time a b
0 2 0.5 -2.0
1 5 0.1 -1.0
2 8 0.5 -1.0
</code></pre>
<p>The output here may differ from your expected output in some cases if it is po... | python|pandas|group-by | 2 |
4,781 | 59,462,450 | Better way to add label data to convolutional neural network? | <p>I am working on an image classification CNN to practice understanding machine learning, and I want to be as vanilla as possible to really get a concrete understanding of what is happening while also remaining somewhat efficient. </p>
<p>I have a directory structure that goes like this:</p>
<pre><code>training fold... | <p>You can create label array same time when you create pixel array.Lets assume your categories are <code>cat=0,dog=1,ducks=2</code>.initialize a empty numpy array and create label array for each folder.and concatenate the each array for get the final labels.</p>
<pre><code>def get_img_array(dir):
labels_arr= np.e... | python|tensorflow|keras|dataset|conv-neural-network | 2 |
4,782 | 59,050,251 | Reshaping array using array.reshape(-1, 1) | <p>I have a dataframe called <code>data</code> from which I am trying to identify any outlier prices.</p>
<p>The data frame head looks like:</p>
<pre><code> Date Last Price
0 29/12/2017 487.74
1 28/12/2017 422.85
2 27/12/2017 420.64
3 22/12/2017 492.76
4 21/12/2017 403.95
</code></pr... | <p>You should be able to fix the error by changing this line:</p>
<pre><code>np_scaled = scaler.fit_transform(data)
</code></pre>
<p>with this:</p>
<pre><code>np_scaled = scaler.fit_transform(data.values.reshape(-1,1))
</code></pre> | python|pandas|numpy|scikit-learn | 4 |
4,783 | 45,239,458 | pip install numpy error - Unmatched " | <p>I am trying to install numpy in a python3 virtual environment</p>
<pre><code>python3 -m venv venv
source venv/bin/activate
pip install numpy
</code></pre>
<p>After running the above, the installation fails with an error something like this...</p>
<pre><code>error Command "gcc ..." failed with exit status 1
Unmat... | <p>When you install numpy using pip, it runs various shell commands to build the parts of numpy that are written in c. Your environment's <code>$SHELL</code> variable will be used to determine which shell to use. In this case, <code>csh</code> is being used but the command in the installation script expects to be able ... | python-3.x|numpy|virtualenv | 0 |
4,784 | 44,927,592 | Pandas Series boxplot not showing correctly | <p>I have a Pandas Series named a, and a.describe() gives this</p>
<pre><code>count 1116.000
mean 211.495
std 1241.612
min 1.000
25% 16.000
50% 20.000
75% 57.000
max 23220.000
</code></pre>
<p>I'd like to create a boxplot out of it so I did <code>a.plot(kind='box')</code>... | <p>Actually, regarding to your values, your box plot is showing up 'correctly' because of your max value : 23220.000. Try playing with xlim and ylim arguments of <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.plot.html" rel="nofollow noreferrer">Pandas plot function</a></p> | python|pandas|plot|boxplot | 2 |
4,785 | 44,881,307 | Pandas How to hide the header when the output need header as a condition to filter the result? | <h2><strong>Solution</strong></h2>
<p>If you hide the header of the output. use the header = None option. And notice that just use it when you are going to print it. For the reason that if you set the header = None when you load the data, the name of the column is unusable to you, so you can't use it to filter the dat... | <p>I think you need parameter <code>names</code> for set column names if does not exist, also <code>header = None</code> can be omit:</p>
<pre><code>#change column names by your data
df = pd.read_excel("packagesum.xlsx", names=['col1','col2','col3', ...])
</code></pre>
<p>And then code can be simplify by <a href="htt... | python|pandas | 2 |
4,786 | 45,035,213 | plot normal distribution with pd.hist | <p>I have a pd.DataFrame which I want to plot and fit a bell curve over. I got as far as plotting the histogram. How do I fit the bell curve?</p>
<pre><code>wordfreq = pd.DataFrame(columns=vocab, index = authors, data = rates)
wordfreq.hist(column='the', grid = False, normed = True, color = '#9ebcda')[:25]
plt.rcPara... | <p>you can use <a href="https://seaborn.pydata.org/" rel="nofollow noreferrer">seaborn</a> package as:</p>
<pre><code>seaborn.distplot(wordfreq[column])
</code></pre> | python|pandas|matplotlib|visualization | 1 |
4,787 | 45,048,615 | Custom pipeline for different data type in scikit learn | <p>I am currently trying to predict whether a kickstarter project will be successful or no depending on a bunch of integer and some text features. I was looking at building a pipeline which would look something like this</p>
<p>Reference : <a href="http://scikit-learn.org/stable/auto_examples/hetero_feature_union.html... | <p>The ItemSelector is returning a Dataframe, not an array. Thats why the <code>scipy.hstack</code> is throwing up error. Change the ItemSelector as below:</p>
<pre><code>class ItemSelector(BaseEstimator, TransformerMixin):
....
....
....
def transform(self, data_dict):
return data_dict[se... | python|pandas|numpy|machine-learning|scikit-learn | 1 |
4,788 | 57,260,056 | How can I get 2 target values? | <p>so I am currently writing a program that can make predictions of longitude and latitude values. So far, my program can make predictions for 1 target value, but I need it to make 2. How should I go about doing that.</p>
<pre><code>column_names = ['longitude', 'Latitude']
raw_dataset = pd.read_csv('loglat.csv', names... | <p>I would suggest using Model API instead of Sequential API.</p>
<pre><code>from tf.keras.layers import Input, Dense
from tf.keras.models import Model
def build_model():
X = Input(shape=[len(train_dataset.keys())])
hidden_1 = Dense(64, activation=tf.nn.relu)(X)
hidden_2 = Dense(64, activation=tf.nn.relu... | python|tensorflow|keras | 0 |
4,789 | 57,267,874 | Time series CNN, trying to use 1,1 input shape | <p>I'm trying to do a CNN 1D for time series.</p>
<p><strong>First issue:</strong>
When trying to use an input shape of [1,1] I get an error:</p>
<pre><code>Error: Negative dimension size caused by adding layer average_pooling1d_AveragePooling1D1 with input shape [,0,128]
</code></pre>
<p><strong>2nd issue</strong>
... | <p><strong>Time series</strong> is a sequence taken at successive equally spaced points in time according to <a href="https://en.wikipedia.org/wiki/Time_series" rel="nofollow noreferrer">wikipedia</a>. The goal of the neural network NN used on time series is to find the pattern between the series of data. Convolutiona ... | tensorflow|tensorflow.js | 1 |
4,790 | 46,103,859 | Reshape list/sequence of integers and arrays to array | <p>I have multiple lists of format
(count_i, 1dim-array_i)
and I would like to convert them to arrays such that they read</p>
<p>[count_i, 1dim-array_i[0], 1dim-array_i[1], 1dim-array_i[2], ... , 1dim-array_i[n]]</p>
<p>If it helps to understand what I mean, here is an example list:</p>
<pre><code>mylist = [[0, arra... | <p>Your <em>list comprehension</em> generates <em>lists with two elements</em> where the second one lis a list. For example for <code>i = 1</code>, it generates:</p>
<pre><code>>>> [i,[mylist[i][1][j] for j in range(12)]]
[1, [1.0, 0.68744907, 0.38420842999999999, 0.25922927000000001, 0.047196139999999998, 0.... | python|arrays|list|numpy|reshape | 0 |
4,791 | 46,091,924 | Python: How to drop a row whose particular column is empty/NaN? | <p>I have a csv file. I read it:</p>
<pre><code>import pandas as pd
data = pd.read_csv('my_data.csv', sep=',')
data.head()
</code></pre>
<p>It has output like:</p>
<pre><code>id city department sms category
01 khi revenue NaN 0
02 lhr revenue good 1
03 lhr rev... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html" rel="noreferrer"><code>dropna</code></a> with parameter <code>subset</code> for specify column for check <code>NaN</code>s:</p>
<pre><code>data = data.dropna(subset=['sms'])
print (data)
id city department sms cat... | python|pandas|dataframe | 72 |
4,792 | 45,879,776 | TensorFlow how to make results reproducible for `tf.nn.sampled_softmax_loss` | <p>I would like to get reproducible results for my tensorflow runs. The way I'm trying to make this happen is to set up the numpy and tensorflow seeds:</p>
<pre><code>import numpy as np
rnd_seed = 1
np.random.seed(rnd_seed)
import tensorflow as tf
tf.set_random_seed(rnd_seed)
</code></pre>
<p>As well as make sure th... | <p>I finally, found out how to make results reproducible. Just like @Anis suggested I should've set the graph seed and this can be done by:</p>
<pre><code>with graph.as_default(), tf.device('/cpu:0'):
tf.set_random_seed(1234)
</code></pre> | python|numpy|random|tensorflow | 0 |
4,793 | 23,293,011 | How to plot a superimposed bar chart using matplotlib in python? | <p>I want to plot a bar chart or a histogram using matplotlib. I don't want a stacked bar plot, but a superimposed barplot of two lists of data, for instance I have the following two lists of data with me:</p>
<p>Some code to begin with :</p>
<pre><code>import matplotlib.pyplot as plt
from numpy.random import normal,... | <p>You can produce a superimposed bar chart using <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar" rel="noreferrer"><code>plt.bar()</code></a> with the <code>alpha</code> keyword as shown below.</p>
<p>The <code>alpha</code> controls the transparency of the bar. </p>
<p><strong>N.B.</strong> ... | python|numpy|matplotlib|plot|histogram | 19 |
4,794 | 35,425,093 | Reformat pandas DataFrame | <p>I have a <code>pandas</code>.<code>DataFrame</code> with the following data:</p>
<pre><code> country branch Name salary mobile no emailid
x a aa 250000 Null Null
x b bb 350000 8976646410 xx@xx.com
y ... | <p>You can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow"><code>replace</code></a> <code>Null</code> to <code>NaN</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code... | python|pandas | 2 |
4,795 | 35,693,687 | Forcing dependence on a variable update | <p>Say I have some function <code>f</code> of variable <code>x</code>:</p>
<pre><code>x = tf.Variable(1.0)
fx = x*x
</code></pre>
<p>and an op which updates <code>x</code>:</p>
<pre><code>new_x = x.assign(2.0)
</code></pre>
<p>and I want to get the value of <code>f</code> resulting from the updated <code>x</code>. ... | <p>The <code>with tf.control_dependencies([op])</code> block enforces control dependency on <code>op</code> to other ops <em>created</em> within with block. In your case, <code>x*x</code> is created outside, and the <code>tf.identity</code> just gets the old value. Here is what you want :</p>
<pre><code>with tf.contro... | python|tensorflow | 2 |
4,796 | 35,703,963 | Trying to compute softmax values, getting AttributeError: 'list' object has no attribute 'T' | <p>First off, here is my code: </p>
<pre><code>"""Softmax."""
scores = [3.0, 1.0, 0.2]
import numpy as np
def softmax(x):
"""Compute softmax values for each sets of scores in x."""
num = np.exp(x)
score_len = len(x)
y = [0] * score_len
for index in range(1,score_len):
y[index] = (num[ind... | <p>As described in the comments, it is essential that the output of <code>softmax(scores)</code> be an array, as lists do not have the <code>.T</code> attribute. Therefore if we replace the relevant bits in the question with the code below, we can access the <code>.T</code> attribute again. </p>
<pre><code>num = np.e... | python|list|numpy|attributes|softmax | 4 |
4,797 | 28,833,074 | Aggregate group with multi-level columns | <p>I have a grouped DataFrame which i want to aggregate with a dictionary of functions which should map to certain columns. For single-level columns this is straightforward with <code>groups.agg({'colname': <function>})</code>. I am struggling however to get this working with multi-level columns, from which i onl... | <p>I don't think there is a short-cut for this. Fortunately, it is not too hard to build the desired dict explicitly:</p>
<pre><code>result = groups.agg(
{(k1, k2): funcs[k1] for k1, k2 in itertools.product(lev1,lev2)})
</code></pre>
<hr>
<pre><code>import itertools
import numpy as np
import pandas as pd
lev1 =... | python|pandas | 4 |
4,798 | 50,690,276 | Difference between tf.random_normal() and tf.random_normal_initializer() | <p>I'm learning Tensorflow these days.
When using random variables, I noticed there are two different versions. One is the API such as <code>tf.random_normal()</code> and the others are APIs like <code>tf.random_normal_initialize()</code>. I think those two are doing exactly the same things. The following is an example... | <p>Did you have a look at the respective implementations? The initializer (defined <a href="https://github.com/tensorflow/tensorflow/blob/r1.8/tensorflow/python/ops/init_ops.py" rel="nofollow noreferrer">here</a>) is a class that internally calls <code>tf.random_normal()</code>, which is just an operation (defined <a h... | tensorflow|random | 1 |
4,799 | 20,850,219 | Speed performance improvement needed. Using nested for loops | <p>I have a 2D array shaped (1002,1004). For this question it could be generated via:</p>
<pre><code>a = numpy.arange( (1002 * 1004) ).reshape(1002, 1004)
</code></pre>
<p>What I do is generate two lists. The lists are generated via:</p>
<pre><code>theta = (61/180.) * numpy.pi
x = numpy.arange(a.shape[0]) ... | <p>It's possible to return an <em>array</em> of elements form a 2d array by doing <code>a[x, y]</code> where <code>x</code> and <code>y</code> are both integer arrays. This is called advanced indexing or sometimes <a href="http://wiki.scipy.org/Tentative_NumPy_Tutorial#head-0dffc419afa7d77d51062d40d2d84143db8216c2" rel... | python|arrays|performance|for-loop|numpy | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.