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
352,000
51,650,855
How to split column from DataFrame with Pandas
<p>I am reading a CSV file from an API call into a data frame with pandas for some data manipulation.</p> <p>Currently, I'm getting this response:</p> <pre><code>n [78]: dfname Out[78]: productID amountInStock index index_col 7 1.0 NaN 1 7 19 4.0 ...
<blockquote> <p>But the problem is that the 'productID' series has two columns and I can't work out how to split them!</p> </blockquote> <p>Therein lies the misunderstanding. You don't have 2 columns, despite what <code>print</code> tells you. You have one column with an <strong>index</strong>. This is precisely h...
python|pandas|dataframe|indexing|series
2
352,001
51,865,367
Cannot convert the series to <class 'int'`>
<p>I have a set of data with an <em>Age</em> column. I want to remove all the rows that are aged more than 90 and less than 1856.</p> <p>This is the head of the dataframe:</p> <p><a href="https://i.stack.imgur.com/B2wx1.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/B2wx1.jpg" alt="Enter image descr...
<p>Your error is on line 2. <code>df['intage'] = int(df['age'])</code> is not valid, and you can't pass a pandas series to the int function.</p> <p>You need to use <code>astype</code> if df['age'] is object dtype.</p> <pre><code>df['intage'] = df['age'].astype(int) </code></pre> <p>Or since you are subtracting two dat...
python|pandas
38
352,002
51,603,520
Pandas: remove duplicates that exist in any order
<p>My question is similar to <a href="https://stackoverflow.com/questions/40474799/pandas-remove-reverse-duplicates-from-dataframe">Pandas: remove reverse duplicates from dataframe</a> but I have an additional requirement. I need to maintain row value pairs. </p> <p>For example: </p> <p>I have <code>data</code> where...
<p>I think that you can do this with <code>stack</code>, <code>drop_duplicates</code> and <code>unstack</code>:</p> <pre><code>data.set_index(['A','B']).stack().drop_duplicates().unstack().reset_index() A B C D 0 0 50 a y 1 10 22 b c 2 11 35 r w 3 21 5 x z </code></pre>
python|pandas
7
352,003
51,608,879
Weights Matrix Final Fully Connected Layer
<p>My question is, I think, too simple, but it's giving me headaches. I think I'm missing either something conceptually in Neural Networks or Tensorflow is returning some wrong layer. </p> <p>I have a network in which last layer outputs 4800 units. The penultimate layer has 2000 units. I expect my weight matrix for la...
<p>Conceptually, a neural network layer is often written like <code>y = W*x</code> where * is matrix multiplication, <code>x</code> is an input vector and <code>y</code> an output vector. If <code>x</code> has 2000 units and y 4800, then indeed <code>W</code> should have size <code>(4800, 2000)</code>, i.e. 4800 rows a...
python-3.x|tensorflow|conv-neural-network
4
352,004
51,882,170
Connect to google collab with ssh from console from PC
<p>I've found one instruction on the net how to do it:</p> <pre><code>#Generate root password import random, string password = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(20)) #Download ngrok ! wget -q -c -nc https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip ! unzip -qq ...
<p>I had your same issue. To solve it you have to ssh to the instance as root user:</p> <pre><code>ssh root@0.tcp.ngrok.io -p &lt;your_port&gt; </code></pre> <p>And then when it prompts you for a password you have to paste the password that's randomly generated at the beginning of the script (found in the <code>passw...
tensorflow|ssh|ssh-tunnel
6
352,005
51,997,053
Converting normal matrix to numpy
<p>The purpose of this code is to arrange the lines, using the third column as a parameter. If I use normal matrix, the program works just fine, but I need to use numpy, because it's part of a bigger program. </p> <p>The desired output is : [[2,-2,7],[-1,1,4],[10,7,1]]</p> <pre><code>import numpy as np y = np.matrix...
<p>"The purpose of this code is to arrange the lines, using the third column as a parameter.":</p> <pre><code>&gt;&gt;&gt; y = y[np.argsort(y[:,-1].T),:] &gt;&gt;&gt; y matrix([[[10, 7, 1], [-1, 1, 4], [ 2, -2, 7]]]) </code></pre> <p>Like this? </p>
python|python-3.x|numpy
1
352,006
51,868,410
Can't read a .CSV file in Spyder (Python 3.6) and it's not a path or character issue
<p>I'm new in python, I'm learning it so, please, try to be simple when answer me =) thx since now! I'm using Spyder (Python 3.6) and trying to run these lines:</p> <pre><code>import pandas as pd df=pd.read_csv(r'Legumes.csv') df </code></pre> <p>But, I'm having every possible kind of error, and trust me, I read and ...
<p>Your path needs to be absolute <br><br> On <strong> Mac / Linux </strong></p> <pre><code> ‘/path/to/legumes.csv’ </code></pre> <p>Pro-Tip: You can get the full path by right clicking on the file while holding option key, then select “copy legumes.csv as pathname”</p> <p><br><br> On <strong>Windows </strong></p> ...
python|pandas|csv
0
352,007
51,611,378
Remove top row from a dataframe
<p>I have a dataframe that looks like this:</p> <pre><code> level_0 level_1 Repo Averages for 27 Jul 2018 0 Business Date Instrument Ccy 1 27/07/2018 GC_AUSTRIA_SUB_10YR EUR 2 27/07/2018 R_RAGB_1.15_10/18 ...
<p>You can try so:</p> <pre><code>df.columns = df.iloc[0] df = df.reindex(df.index.drop(0)).reset_index(drop=True) df.columns.name = None </code></pre> <p>Output:</p> <pre><code> Business Date Instrument Ccy 0 27/07/2018 GC_AUSTRIA_SUB_10YR EUR 1 27/07/2018 R_RAGB_1.15_10/18 EUR 2 27/07/2018 ...
python|pandas|dataframe|drop
6
352,008
51,839,948
Build a numpy sums array from a dictionary with cluster and indices in a matrix
<p>I have one dictionary with cluster number as keys and matrix's indices as values; and one matrix with float64 values.</p> <p>The goal is to produce an array of sums with values in the array corresponding to indices in the dictionary.</p> <pre><code>K_Index = {0: [(0,0),(1,1),(1,2)], 1: [(1,0)], ...
<p><strong>Approach #1</strong></p> <p>Here's one way -</p> <pre><code>In [207]: s = np.r_[W_Matrix.shape[1],1] In [208]: W1D = W_Matrix.flat In [210]: [W1D[np.dot(k, s)].sum() for k in K_Index.values()] Out[210]: [-0.08999999999999986, 0.95, 1.48, 1.2] </code></pre> <p><strong>Approach #2</strong></p> <p>Alterna...
python|arrays|numpy|matrix|sum
2
352,009
51,965,539
Making a prediction from a trained convolution network
<p>Here is my <code>convolution</code> net that creates training data , then trains on this data using a single <code>convolution</code> with <code>relu</code> activation : </p> <pre><code>train_dataset = [] mu, sigma = 0, 0.1 # mean and standard deviation num_instances = 10 for i in range(num_instances) : image ...
<p>As noted by <a href="https://stackoverflow.com/questions/51965539/making-a-prediction-from-a-trained-convolution-network#comment90881190_51965539">Koustav</a> your net is not "fully convolutional": although you have two <code>nn.Conv2d</code> layers, you still have a "fully-connected" (aka <code>nn.Linear</code>) la...
neural-network|deep-learning|computer-vision|conv-neural-network|pytorch
1
352,010
51,883,897
Python 2.**: How to capture output of print statement to variable (not file) in order to pass to pandas df.query() function
<p><strong>EDIT: SOLUTION!!!</strong></p> <p>As it turns out, all I needed to do for this to work was <code>df.query('{}'.format(eval(queryStr)))</code> and Python treated <code>queryStr</code> as if it were the same as <code>print(queryStr)</code>. I don't recommend using <code>eval</code> all of the time, but in thi...
<p>If you prefix the string with 'r', it will indicate to Python that it's a "raw string" and will pass the string <em>exactly</em> as you specify it:</p> <pre><code>df.query(r"your \query") </code></pre> <p>This will pass the string 'y', 'o', 'u', 'r', ' ', '\', 'q', 'u', 'e', 'r', 'y' -- with the one backslash exac...
python|pandas|printing
-1
352,011
51,821,711
Stacking different types of arrays in numpy
<p>I'm having difficulties in stacking different "types" of numpy arrays. </p> <p>array_1 is <code>array([(3,111),(3,222)])</code></p> <p>array_2 is <code>array([(4,111),(4,222)])</code></p> <p>array_3 is <code>array([[5,111],[5,222]])</code></p> <p>(notice the change in brackets in array_3). </p> <p>I can easily ...
<p>convert every array to numpy array and then use np.hstack</p> <pre><code>array_1 = np.array([(3,111),(3,222)]) array_2 = np.array([(4,111),(4,222)]) array_3 = np.array([[5,111],[5,222]]) np.hstack((array_1,array_2,array_3)) </code></pre> <p>I got the following output</p> <blockquote> <p>array([[ 3, 111, 4...
python|numpy
0
352,012
36,177,620
timestamp string (Unix time) to datetime or pandas.Timestamp
<p>From a source I retrieve some data in JSON format. I want to save this data (measurements in time) as a text file. Repeatedly I want to go the same source and see if new measurements are available, if so I want to add it to the other measurements.</p> <p>The data I get looks like this:</p> <pre><code>{"xyz":[{"uni...
<p>use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html#pandas.to_datetime" rel="noreferrer"><code>to_datetime</code></a> and pass <code>unit='s'</code> to treat the value as epoch time after converting the <code>dtype</code> to <code>int</code> using <a href="http://pandas.pydata....
python|datetime|pandas|timestamp|unix-timestamp
11
352,013
35,990,467
Fit mixture of two gaussian/normal distributions to a histogram from one set of data, python
<p>I have one set of data in python. I am plotting this as a histogram, this plot shows a bimodal distribution, therefore I am trying to plot two gaussian profiles over each peak in the bimodality.</p> <p>If i use the code below is requires me to have two datasets with the same size. however I just have one dataset, a...
<p>Here a simulation with scipy tools :</p> <pre><code>from pylab import * from scipy.optimize import curve_fit data=concatenate((normal(1,.2,5000),normal(2,.2,2500))) y,x,_=hist(data,100,alpha=.3,label='data') x=(x[1:]+x[:-1])/2 # for len(x)==len(y) def gauss(x,mu,sigma,A): return A*exp(-(x-mu)**2/2/sigma**2) ...
python|numpy|scipy
33
352,014
35,941,608
Operation on column based on column name pandas
<p>I would like to apply a function only on one column based on its name. For instance, I would like to do something like that</p> <pre><code>df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD')) df['A']*10 df['B']*5 </code></pre> <p>And obviously get df with the column A multiply by 10 and B mul...
<p>You could use <a href="https://www.google.ru/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=1&amp;cad=rja&amp;uact=8&amp;ved=0ahUKEwi5tqvL4LjLAhWCQJoKHc94BXUQFggbMAA&amp;url=http%3A%2F%2Fpandas.pydata.org%2Fpandas-docs%2Fstable%2Fgenerated%2Fpandas.DataFrame.mul.html&amp;usg=AFQjCNFD6MbVHE-wH4xhjKPMLqi3v...
python|pandas
2
352,015
35,894,259
python sparse csr matrix: how to serialize it
<p>I have a csr_matrix, which is constructed as follows:</p> <pre><code>from scipy.sparse import csr_matrix import numpy as np row = np.array([0, 0, 1, 2, 2, 2]) col = np.array([0, 2, 2, 0, 1, 2]) data = np.array([1, 2, 3, 4, 5, 6]) a = csr_matrix((data, (row, col)), shape=(3, 3)) </code></pre> <p>Now to serialize (a...
<p><code>coo</code> format has the values that you want:</p> <pre><code>In [3]: row = np.array([0, 0, 1, 2, 2, 2]) In [4]: col = np.array([0, 2, 2, 0, 1, 2]) In [5]: data = np.array([1, 2, 3, 4, 5, 6]) In [6]: a = sparse.csr_matrix((data,(row,col)), shape=(3,3)) In [7]: a.data Out[7]: array([1, 2, 3, 4, 5, 6]) ...
python|numpy|serialization|scipy|sparse-matrix
2
352,016
36,139,889
RNN model running out of memory in TensorFlow
<p>I implemented a Sequence to Sequence model using the rnn.rnn helper in TensorFlow.</p> <pre><code>with tf.variable_scope("rnn") as scope, tf.device("/gpu:0"): cell = tf.nn.rnn_cell.BasicLSTMCell(4096) lstm = tf.nn.rnn_cell.MultiRNNCell([cell] * 2) _, cell = rnn.rnn(lstm, input_vectors, dtype=tf.float32...
<p>The function <code>tf.gradients</code> as well as the <code>minimize</code> method of the optimizers allow you to set parameter called <code>aggregation_method</code>. The default value is <code>ADD_N</code>. This method constructs the graph in such a way that all gradients need to be computed at the same time. </p>...
tensorflow
5
352,017
36,046,634
Optimizing a simple CPU bound function with python multiprocessing
<p>I am trying to understand how the multiprocessing.Pool works, and I have developed a minimal example that illustrates my question. Briefly, I am using pool.map to parallelize a CPU-bound function operating on an array by following the example <a href="https://stackoverflow.com/questions/20887555/dead-simple-example-...
<p>Turns out your example fits perfectly in the <a href="http://pythran.readthedocs.io/en/latest/" rel="nofollow noreferrer">Pythran</a> model. Compiling the following source code <code>count_even.py</code>:</p> <pre><code>#pythran export count_even(int [:]) import numpy as np def count_even_numbers(x): return np...
python|performance|numpy|parallel-processing|python-multiprocessing
2
352,018
36,191,770
Py2Exe, [Errno 2] No such file or directory: 'numpy-atlas.dll'
<p>I have included matplotlib in my program, I searched about numpy_atlas.dll on google and I seem to be the only one on Earth with this problem.</p> <h1>setup.py</h1> <pre><code>from setuptools import setup import py2exe setup(console=['EulerMethod.py']) </code></pre> <h1>Running Py2Exe results in error</h1> <pre><co...
<p>This is what worked for me. I found the dll: C:\Python27\Lib\site-packages\numpy\core\numpy-atlas.dll and copied it to the same folder that has the setup.py</p>
python|numpy|matplotlib|py2exe
17
352,019
36,137,200
AttributeError: 'module' object has no attribute 'version'
<p>I am working on learning how to use pandas but get the following error:</p> <pre><code>Traceback (most recent call last): File "data_frame.py", line 2, in &lt;module&gt; import pandas as pd File "/Users/gregwinter/anaconda2/lib/python2.7/site-packages/pandas/__init__.py", line 13, in &lt;module&gt; __im...
<p>You named a file of your <em>own</em> <code>numpy.py</code>:</p> <pre><code>/Users/gregwinter/numpy.py </code></pre> <p>Guess which one Python thinks pandas wants to import? :-) Rename your program, and remove any .pyc or .pyo files that are around.</p>
python-2.7|pandas
6
352,020
36,025,188
Along what axis does mpi4py Scatterv function split a numpy array?
<p>I have the following MWE using <code>comm.Scatterv</code> and <code>comm.Gatherv</code> to distribute a 4D array across a given number of cores (<code>size</code>)</p> <pre><code>import numpy as np from mpi4py import MPI import matplotlib.pyplot as plt comm = MPI.COMM_WORLD size = comm.Get_size() rank = comm.Get_r...
<p><code>comm.Scatterv</code> and <code>comm.Gatherv</code> do not know anything about the numpy array dimensions. They just see the <code>sendbuf</code> as a block of memory. Therefore it is necessary to take this into account when specifying the <code>sendcounts</code> and <code>displacements</code> (see <a href="htt...
python|arrays|numpy|mpi4py
6
352,021
36,232,570
removing duplicates from a column of arrays
<p>I have a series with a key column that has dates (DateTime Index) in chronological order, and a value column that has arrays. I would like to preserve order and delete individual elements in each row array that appear in a previous row array.</p> <p>Data:</p> <pre><code>Created 2015-02-08 [X, Y, Z, A] 2015-02-1...
<p>You can first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow"><code>apply</code></a> <code>Series</code> from <code>lists</code>, then create one column with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nof...
python|arrays|pandas|duplicates
1
352,022
35,864,149
efficiently set a large number of SciPy sparse matrix entries to zero
<p>I need to prune a large number of entries from a SciPy sparse matrix. Currently I convert the matrix to the DOK format and individually assign each entry to 0.</p> <pre><code>m = m.todok() for i, j in pruneme: m[i,j] = 0 </code></pre> <p>This is extremely slow.</p> <p>Is there a faster way?</p>
<p>You can set elements of CSR sparse arrays efficiently, as long as you do not add new nonzeros, simply by subscripting the array with tuples:</p> <pre><code>i, j = zip(*pruneme) # assuming that pruneme is a python list m[i, j] = 0. m.eliminate_zeros() </code></pre> <p>That should be much faster than constructing tw...
python|numpy|matrix|scipy|sparse-matrix
4
352,023
36,104,060
Pandas complex processing with groupby
<p>My data is grouped by id. In each group, it is sorted by colB. The logic I need to implement is as follows:</p> <p>If colA is blank, and colD is either (2,3, or 4), then create a column called 'flag' and set flag = 1 in the last non-zero row of colC. Set the flag to 0 in all the other rows of that group, where c...
<p>It looks like there are three parts to your process:</p> <p>1) Get rid of rows where colA is null and colC == 0. Work on reducing your dataframe first</p> <p>if it is AND logic:</p> <p><code>reduced_df = df.loc[(df.colA.notnull()) &amp; (df.colC != 0), :].copy()</code></p> <p>if it is OR logic:</p> <pre><code>r...
python|pandas
0
352,024
36,133,447
pandas printing `tput: unknown terminal "emacs"`
<p>I'm using <code>pandas</code> installed via Anaconda on Windows 10.</p> <p>I run an IPython terminal inside an emacs inferior Python shell.</p> <p>Every time I print a <code>pandas.DataFrame</code> to the terminal, I get an error message <code>tput: unknown terminal "emacs"</code>.</p> <p>The error message is the...
<p>The fix that "jurasource" suggested was to inspect the <code>PATH</code> to see if there are any elements of the path that would not be recognized by windows but would instead be recognized by a unix-like operating system. That is why <code>/git/bin</code> would be an issues, that path is recognizable by a unix-like...
python|shell|pandas|emacs|ipython
1
352,025
36,234,538
Why does fftfreq produce negative values?
<p>From the documentation for <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.fft.fftfreq.html" rel="nofollow">fftfreq</a>:</p> <pre><code>&gt;&gt;&gt; signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5], dtype=float) &gt;&gt;&gt; fourier = np.fft.fft(signal) &gt;&gt;&gt; n = signal.size &gt;&gt;&gt;...
<p>It's inherent to FFT algorithm. The second half of FFT array is the conjugate of the first half, so don't contain any new information.</p> <p>To visualize the spectrum, just use the first half.</p> <pre><code>f=freq[:n/2] s=abs(fourier[:n/2]) plot(f,s) </code></pre>
python|numpy
5
352,026
36,008,510
numpy linspace and mesh grid for multiple dimensions
<p>I am porting some matlab code to python using numpy and I have the following matlab command:</p> <pre><code>[xgrid,ygrid]=meshgrid(linspace(-0.5,0.5, GridSize-1), ... linspace(-0.5,0.5, GridSize-1)); </code></pre> <p>Now, this is fine in 2D but I would like to extend this to n-dimensional. S...
<p>You could use loop comprehension to generate all 1D arrays and then use <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.meshgrid.html" rel="nofollow"><code>np.meshgrid</code></a> on all those with <code>*</code> operator that internally does <a href="https://docs.python.org/2/tutorial/contr...
python|matlab|numpy
6
352,027
37,533,170
Selecting rows based on criteria from another dataframe
<p>I have two <code>DataFrames</code> with different numbers of rows and columns, but which have at least one column containing some common information. Specifically, <code>StationCode</code> is always a <code>LocationCode</code>:</p> <pre><code>dataframe1.head() DistanceToPrev LineCode SeqNum StationCode ...
<p>Simple solution would be:</p> <pre><code>df2 = df2.merge(df1[['StationCode', 'RailTime']], left_on='LocationCode', right_on='StationCode') df2 = df2[df2.Min&lt;df2.RailTime] </code></pre>
python|pandas
2
352,028
37,467,515
Python find index of all array elements in another array
<p>I am trying to do the following: </p> <pre><code>import numpy as np A = np.array([1,5,2,7,1]) B = np.sort(A) print B &gt;&gt;&gt; [1,1,2,5,7] </code></pre> <p>I want to find the location of all elements in B as in original array A. i.e. I want to create an array C such that</p> <pre><code>print C &gt;&gt;[0,4,2,1...
<pre><code>import numpy as np A = np.array([1,5,2,7,1]) print np.argsort(A) #prints [0 4 2 1 3] </code></pre>
python|numpy
9
352,029
37,183,765
Selecting axis form multidimensional arrays with an array
<p>I am trying to select a subset of a multidimensional array using another array, so for example, if I have:</p> <pre><code>a=np.linspace(1,30,30) a=a.reshape(5,3,2) </code></pre> <p>I would like to take the subset [:,0,1], which I can do by saying</p> <pre><code>a_subset=a[:,0,1] </code></pre> <p>but, is there an...
<p>You can do this using <code>numpy.index_exp</code> (<a href="https://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.s_.html#numpy.s_" rel="nofollow">docs</a>) as follows:</p> <pre><code>import numpy as np a = np.linspace(1, 30, 30) a = a.reshape(5, 3, 2) b = np.index_exp[:,0,1] a_subset = a[b] </code><...
python|arrays|numpy|subset|slice
4
352,030
37,466,614
How to merge two data frames based on different column names
<pre><code>import pandas as pd left = pd.DataFrame({'A': ['A1', 'A1', 'A2', 'A3'], 'B': ['B0', 'B1', 'B2', 'B3'], 'C': ['K0', 'K1', 'K0', 'K1']}) right = pd.DataFrame({'AA': ['A1', 'A3'], 'BB': ['B0', 'B3'], 'CC': ['K0', 'K1'], ...
<p>Use pandas <code>merge</code> method with <code>left_on</code> and <code>right_on</code> parameters.</p> <pre><code>left.merge(right, how='left', left_on=['A', 'B', 'C'], right_on=['AA', 'BB', 'CC'])[['A', 'B', 'C', 'DD']] </code></pre> <p>gets you:</p> <pre><code> A B C DD 0 A1 B0 ...
python|pandas
2
352,031
37,417,889
Sorting values in one column that contains NAs by the order of another column
<p>I have a dataframe in pandas</p> <pre><code>import pandas as pd df=pd.DataFrame.from_dict({'col1':['A_2','A_1','A_3','A_4','A_6','A_5','A_8','A_7'], 'col2':['NaN','A_2','A_3','A_4','A_5','NaN','A_1','A_6']}, orient='index').T </code></pre> <p>I want to change the order of the second column, <code>col2</code> and ...
<p>If I understand correctly, you can rewrite <code>col2</code> with values from <code>col1</code> when they exist in <code>col2</code>:</p> <pre><code>df.col2 = df.col1[df.col1.isin(df.col2)] </code></pre> <p>Result:</p> <pre><code>df Out[13]: col2 col1 0 A_2 A_2 1 A_1 A_1 2 A_3 A_3 3 A_4 A_4 4 A_6 A_6...
python|pandas
2
352,032
37,421,314
how to find the exact location of maximum value from data frame in Python 3.5- modified
<p>I have one DataFrame in Python 3.5, such as:</p> <pre><code>In [1]:tway5new.info() &lt;class 'pandas.core.frame.DataFrame'&gt; Index: 44 entries, to VOI Columns: 43802 entries, 2011-01-01 00:00:00 to 2015-12-31 23:00:00 dtypes: int64(43802) memory usage: 14.7+ MB </code></pre> <p>And the column name for this ...
<p>IIUC you'd be better off making the columns the index and then you can <code>resample</code> or filter on the day:</p> <pre><code>df = tway5new.T </code></pre> <p>then you downsample</p> <pre><code>df.resample('d') </code></pre> <p>or group on the day:</p> <pre><code>df.groupby([df.index.year, df.index.month, d...
python|pandas|groupwise-maximum
0
352,033
37,383,137
Neural network model not learning?
<p>I tried to model a NN using softmax regression. After 999 iterations, I got error of about 0.02% for per data point, which i thought was good. But when I visualize the model on tensorboard, my cost function did not reach towards 0 instead I got something like <a href="http://i.stack.imgur.com/3k35I.png" rel="nofoll...
<p>I got the same plot like you a couple of times.</p> <p>That happened mostly when I was running tensorboard on multiple log-files. That is, the logdir I gave to TensorBoard contained multiple log-files. Try to run TensorBoard on one single log-file and let me know what happens</p>
machine-learning|neural-network|tensorflow|deep-learning
0
352,034
37,575,192
Business days between two columns of dates with Pandas Groupby
<p>I have a <code>Dataframe</code> in <code>Pandas</code> with a letter and two dates as columns. I would like to calculate the difference between the two date columns for the previous row using <code>shift(1)</code> provided that the <code>Letter</code>value is the same (using a <code>groupby</code>). The complex part...
<p>The following should work - first removing the leading zeros from the date digits):</p> <pre><code>df = pd.DataFrame(data=[['A', datetime(2016, 1, 7), datetime(2016, 1, 9)], ['A', datetime(2016, 3, 1), datetime(2016, 3, 8)], ['B', datetime(2016, 5, 1), datetime(2016, ...
python|python-2.7|numpy|pandas
1
352,035
37,593,550
replace() method not working on Pandas DataFrame
<p>I have looked up this issue and most questions are for more complex replacements. However in my case I have a very simple dataframe as a test dummy.</p> <p>The aim is to replace a string anywhere in the dataframe with an nan, however this does not seem to work (i.e. does not replace; no errors whatsoever). I've trie...
<p>Given that this is the top Google result when searching for "Pandas replace is not working" I'd like to also mention that:</p> <blockquote> <p>replace does full replacement searches, unless you turn on the regex switch. Use regex=True, and it should perform partial replacements as well.</p> </blockquote> <p>...
python|pandas|dataframe|numpy|replace
132
352,036
37,547,914
AttributeError: 'numpy.ndarray' object has no attribute 'lower' fitting logistic model data
<p>I am running this code:</p> <pre><code>from sklearn import cross_validation import numpy as np import sys import pandas as pd import matplotlib.pyplot as plt from sklearn import datasets, svm, metrics digits = datasets.load_digits() X_train, X_test, y_train, y_test = cross_validation.train_test_split( digits.data...
<p>You shouldn't pass <code>X_train</code> and <code>y_train</code> to <code>LogisticRegression</code> constructor. You need just</p> <pre><code>... clf = linear_model.LogisticRegression() clf.fit(X_train, y_train) </code></pre>
python|numpy|scikit-learn
3
352,037
37,519,618
Creating Multi-hierarchy pivot table in Pandas
<h3>1. Background</h3> <p>The .xls files I have now contain some parameters of multi-pollutant in many aspects for different sites. </p> <p>I created an simplified dataframe below as an illustration:</p> <p><a href="https://i.stack.imgur.com/OLu1y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/...
<p>IIUC</p> <p>You want the same dataframe, but with a better column index.</p> <p>To create the first level:</p> <pre><code>level0 = df.columns.str.extract(r'([^\d]*)', expand=False) </code></pre> <p>then assign a multiindex to the columns attribute.</p> <pre><code>df.columns = pd.MultiIndex.from_arrays([level0, ...
python|excel|pandas|pivot-table
1
352,038
37,444,363
how expensive are RuntimeWarning warnings on performance for computation on big data
<p>I have many situations where computations encounter things like:</p> <pre><code>-divide by zero -np.nan values in a column that I compute df['col'].quantile(0.5) -np.nan values in groupby objects that are then used like grouped.agg('sum') </code></pre> <p>etc</p> <p>I don't get any errors but do get <code>Runtime...
<p>A warning amounts to several simple operations, including hashing to determine if a warning has already been issued and whether that warning should be issued more than once, and where the warning occurred. These are fast, but they aren't free.</p> <p>All those operations occur regardless of whether a warning is act...
python|pandas|warnings|runtimeexception
1
352,039
37,206,649
Create pandas period range without leap days
<p>I'm working with a scientific model that doesn't consider leap days - every year has exactly 365 days.</p> <p>I want to create a pandas period range without leap days. Is this the best way to achieve it?</p> <pre><code>#!/usr/bin/env python import pandas periods = pandas.period_range('1900-01-01', '2019-12-31') is...
<p>I've written a wrapper function for <code>period_range</code> that provides a <code>without_leap</code> keyword argument.</p> <pre><code>def period_range(*args, without_leap=False, **kwargs): """Wraps period_range, removing leap days""" periods = pandas.period_range(*args, **kwargs) if without_leap: ...
python|pandas
0
352,040
37,415,118
pandas initialize dataframe column cells as empty lists
<p>I need to initialize the cells in a column of a <code>DataFrame</code> to <code>lists</code>.</p> <pre><code>df['some_col'] = [[] for _ in no_of_rows] </code></pre> <p>I am wondering is there a better way to do that in terms of time efficiency?</p>
<p>Since you are looking for time efficiency, below some benchmarks. I think <code>list</code> comprehension is already quite fast to create the empty <code>list</code> of <code>list</code> objects, but you can squeeze out a marginal improvement using <code>itertools.repeat</code>. On the <code>insert</code> piece, <co...
python|python-3.x|pandas|dataframe|series
6
352,041
37,272,603
How to efficiently pass initial value to get_variable
<p>I want to create a variable using <code>tf.get_variable</code> and it should be initialized with a numpy array.</p> <p>As far as I know, there are two ways to create a variable, <code>tf.Variable</code> and <code>tf.get_variable</code>. We can easily pass initial values to variables created by <code>tf.Variable</co...
<p>The answer is to use the function <code>tf.constant_initializer(value)</code> of TensorFlow (cf.<a href="https://www.tensorflow.org/api_docs/python/tf/keras/initializers/Constant" rel="nofollow noreferrer">doc</a>).</p> <p>Although the documentation says to use only scalar values, you can pass a numpy array of any ...
python|neural-network|tensorflow
5
352,042
37,600,711
Pandas split column into multiple columns by comma
<p>I am trying to split a column into multiple columns based on comma/space separation.</p> <p>My dataframe currently looks like</p> <pre><code> KEYS 1 0 FIT-4270 4000.0439 1 FIT-4269 ...
<p>In case someone else wants to split a single column (deliminated by a value) into multiple columns - try this:</p> <pre><code>series.str.split(',', expand=True) </code></pre> <p>This answered the question I came here looking for. </p> <p>Credit to <a href="https://stackoverflow.com/users/704848/edchum">EdChum's</...
python|pandas|csv|dataframe|split
70
352,043
37,370,656
"not in" comparison not working as expected
<p>I am having trouble with the <code>not in</code> comparison operator in Python 2.7. I have a list of US state abbreviations, and I want to check if a given abbreviation is not in that list, so I use:</p> <pre><code>'IL' not in states['Abbreviation'] </code></pre> <p>Unexpectedly, I got a True; however, when I do t...
<p>It looks like your <code>states</code> is not a list, but a pandas DataFrame, and <code>states['Abbreviation']</code> is one of its columns (a pandas Series). Using <code>in</code> on a Series checks whether the value is in the index, not the values. Try <code>'IL' in states['Abbreviation'].values</code>.</p>
python|python-2.7|pandas|string-comparison
7
352,044
37,413,147
Convert `int *` to a Python or Numpy object in a Cythonized function
<p>(I think this question can easily be answered by an expert without an actual copy-paste-working-example, so I did not spent extra time on it…)</p> <p>I have a C++ method, which returns an array of integers:</p> <pre><code>int* Narf::foo() { int bar[10]; for (int i = 0; i &lt; 10; i++) { bar[i] = i;...
<p>To wrap it a numpy array, you need to know the size, then you can do it like this:</p> <pre><code>def foo(self): cdef int[::1] view = &lt;int[:self.c_narf.size()]&gt; self.c_narf.foo() return np.asarray(view) </code></pre> <p>The above code assumes that there exists a function <code>self.c_narf.size()</cod...
python|numpy|cython|cythonize
2
352,045
41,958,921
Tensorflow graph editor reroute complex network
<p>I try to wrap operation with customized operation.<br /> I solved input of target operation (A in picture) but fail with wrapping output.</p> <p>Init network operations looks like it.</p> <pre><code> C D / \ / B A </code></pre> <p>and assume every operation has 1 output tensor. I want to add operation 'E'</p> <pr...
<p>You need to do some subgraph <a href="https://www.tensorflow.org/api_docs/python/contrib.graph_editor/module_subgraph#SubGraphView.remap_outputs" rel="noreferrer">remapping</a> to make sure the signatures of the two subgraphs match. To do so it's helpful to print the subgraph.</p> <pre><code>tf.reset_default_graph(...
python|tensorflow
5
352,046
42,069,025
Pandas timeseries indexing fails when the index is hierarchical
<p>I tried the following code snippet.</p> <pre><code>In [84]: from datetime import datetime from dateutil.parser import parse ​ rng = [datetime(2017,1,13), datetime(2017,1,14), datetime(2017,2,15), datetime(2017,2,16)] ​ s = Series([1,2,3,4], index=rng) ​s['2017/1'] Out[84]: 2017-01-13 1 2017-01-14 2 dtype: in...
<p>It seems it is more complicated.</p> <p><a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#partial-string-indexing-on-datetimeindex-when-part-of-a-multiindex" rel="nofollow noreferrer"><code>Partial string indexing on datetimeindex when part of a multiindex</code></a> is implemented in <code>DataFra...
pandas|time-series
1
352,047
42,099,216
convert a dataframe to multiple index dataframe
<p>May be fairly easy to convert to multiple indexes but I could not get my head around it. I have the following dataframe that I would like to convert to multiple indexes. </p> <p>My Input dataframe:</p> <pre><code>mydf= pd.DataFrame({'id':['dataid1','dataid2','dataid1','dataid1','dataid2'],'Ref':['Ref1','Ref2','Re...
<p>You can make a <code>rowid</code> column to indicate the correspondence between rows from different ids, then do the <code>unstack/pivot</code>:</p> <pre><code>(mydf.assign(rowid = mydf.groupby('id').cumcount()) .set_index(['id', 'rowid']).unstack(level=0) .swaplevel(axis=1).sort_index(axis=1)) </code></p...
python|pandas
4
352,048
41,802,641
Series with count larger than certain number
<p>Given this code in iPython</p> <pre><code>df1=df["BillingContactCountry"].value_counts() df1 </code></pre> <p>I get </p> <pre><code>United States 4138 Germany 1963 United Kingdom 732 Switzerland 528 Australia ...
<p>You need<a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a>:</p> <pre><code>print (df1[df1 &gt; 303]) United States 4138 Germany 1963 United Kingdom 732 Switzerland 528 Australia 459 Canada...
pandas
3
352,049
41,987,780
Grow a pandas panel along major_axis with a stream of new data?
<p>My application has a stream of incoming data of the form</p> <pre><code>name, datetime, {x, y, z} </code></pre> <p>or in other words, I receive single rows of data, with columns <code>name, datetime, x, y, z</code>. I get bursts of data, every few minutes, some of which is new.</p> <p>I want to store this data in...
<p>I'd say scrap the panel for now and use a dataframe with a <code>pd.Multi-Index</code></p> <p><strong><em>sample data</em></strong><br> assuming <code>'x', 'y', 'z'</code> come in a tuple</p> <pre><code>data = [ ['a', pd.Timestamp('2016-03-31'), (1, 2, 3)], ['a', pd.Timestamp('2016-04-30'), (1, 2, 3)], ...
python|pandas|time-series|containers|panel
3
352,050
41,878,145
getting ROC curve from createLBPHFaceRecognizer
<p>I'm using <a href="http://docs.opencv.org/2.4/modules/contrib/doc/facerec/facerec_tutorial.html#local-binary-patterns-histograms" rel="nofollow noreferrer">LBPHFaceRecognizer</a> on a face database.</p> <p>I need to create a ROC curve of my results for a collage assignment. </p> <p>from the predict function i get ...
<p>if you have the true value, and the predicted value, you can use sklearn builtin metric function:</p> <p><a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_curve.html" rel="nofollow noreferrer">http://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_curve.html</a></p> <p>hop...
python-2.7|opencv|numpy|image-processing
0
352,051
41,840,513
Tensorflow make Training Testing dataset from images
<p>I am making an image classifier I downloaded images of 2 classes to 2 folders:</p> <pre><code>├── Demo │ ├── pizza │ |── lasagnia </code></pre> <p>How can I make a training and testing dataset of images in tensorflow by shuffling the images and spliting into training and testing sets.</p>
<p>Following should work: <code>tf.split_v(tf.shuffle(images, ...), ...)</code></p>
python|python-3.x|tensorflow|dataset
0
352,052
41,980,098
pandas dataframe dtypes compare equality
<p>How can I see which <code>dtypes</code> in a pandas data frame are not equal?</p> <p>I.e. to find out why <code>df1.dtypes.equals(df2.dtypes)</code> returns <code>False</code></p>
<p>So long as the column names match and you have the same number of columns then you can just compare the <code>dtypes</code> directly:</p> <pre><code>In [152]: df1 = pd.DataFrame({'int':np.arange(5), 'flt':np.random.randn(5)}) df2 = pd.DataFrame({'int':np.random.randn(5), 'flt':np.random.randn(5)}) df1.dtypes == df2...
python|pandas|equality
5
352,053
42,028,066
TensorFlow CSV import: adding features and labels to Summary for TensorBoard reads double the lines
<p>I have a very basic TensorFlow app to test loading the data from CSV line-by-line and adding various summaries and visualizations to TensorBoard. My input CSV file has 18 rows and a bunch of columns -- first XX columns are 'features' and subsequent YY columns are 0s and 1s representing the label.</p> <p>I noticed t...
<p>The issue is that each session.run call pulls from the queue (the first one does it explicitly, the second because the summary ops rely on queue data). Rather than using feed_dict to feed previously pulled data, if you instead have the summaries and the actual use of the queue data in the same session.run call, ther...
python|tensorflow
1
352,054
41,870,108
df.loc causes a SettingWithCopyWarning warning message
<p>The following line of my code causes a warning :</p> <pre><code>import pandas as pd s = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD')) s.loc[-1] = [5,np.nan,np.nan,6] grouped = s.groupby(['A']) for key_m, group_m in grouped: group_m.loc[-1] = [10,np.nan,np.nan,10] C:\Anaconda3\lib\...
<p>The documentation is slightly confusing.</p> <p>Your <code>dataframe</code> is a copy of another <code>dataframe</code>. You can verify this by running <code>bool(df.is_copy)</code> You are getting the warning because you are trying to assign to this copy.</p> <p>The warning/documentation is telling you how you ...
python|pandas|chained-assignment
14
352,055
41,992,978
Need advice on speeding up the python code on data cleaning
<p>I'm running a side data analysis project using python notebook (jupyter). The dataset has ~1.3 rows, and the first thing I want to do it to extract day, month and year from the 'date' column in datasets. The code I wrote executes well except it takes really long time. I estimated it could take an hour and half to fi...
<p>This is how I would extract the year, month, and day from an existing dataframe into a new dataframe:</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame({'date' : pd.date_range("19970202", periods=365*20)}) df2 = pd.DataFrame({'year' : df['date'].dt.year, 'month' : df['date'].dt.month, 'day' ...
python|algorithm|pandas|data-analysis|data-science
0
352,056
41,723,117
How to report issues on Tensorflow website?
<p>How can I report an issue on Tensorflow website? I am not talking about the API, but everything else, e.g. installation instructions and tutorials. </p> <p>For instance, installation instructions indicate that Tensorflow for Python 3.5 and GPU requires CuDNN v5, but that is incorrect, as with CuDNN v5 it doesn't wo...
<p>Please open an issue at the TensorFlow GitHub Issues page: <a href="https://github.com/tensorflow/tensorflow/issues" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/issues</a></p>
tensorflow|cudnn
3
352,057
41,831,956
How can I read the csv file in pandas which is separated with ";"?
<p>I started working with pandas in python 3.4 for couple of days. I chose to work on <a href="http://www2.informatik.uni-freiburg.de/~cziegler/BX/" rel="nofollow noreferrer">Book-Crossing data set</a>.<br/> The book information table is like this:<br/><br/> <a href="https://i.stack.imgur.com/Pm9PI.png" rel="nofollow n...
<p>In the first and second row, change <code>sep</code> to <code>;</code>.</p> <pre><code>sep=';' </code></pre>
python-3.x|csv|pandas|dataset
0
352,058
41,977,506
Pandas pivot_table : a very surprising result with aggfunc len(x.unique()) and margins=True
<p>I am using pandas pivot_table with aggfunc=lambda x: len(x.unique()) with margins=True. But I get a very surprising results : the column 'All' do not display to the sum of the rows values ! The results in column 'All' is systematically less than the sum.</p> <p><a href="https://i.stack.imgur.com/hpoNi.jpg" rel="nof...
<p>After spending several hours checking all the data and using the Excel pivot table function to understand what was happening here, I found the following (and very surprising) explanation: margins=True does NOT calculate the sum of rows, but re-executes the aggfunc = lambda x: len (x.unique ()) command by applying it...
python|pandas|unique|pivot-table
2
352,059
41,851,619
Applying a function element-wise to a tensor with different parameters in Tensorflow
<p>I have a list that consists of a mix of constants and variables that act as inputs for a function I am trying to optimize. Here is the complex part: I need to apply a function to each of the elements in that list each of them with different parameters. I believe that this must be done in the computation graph to be ...
<p>Use <a href="https://www.tensorflow.org/api_docs/python/functional_ops/higher_order_operators#map_fn" rel="nofollow noreferrer">tf.map_fn</a>. </p> <pre><code>g = tf.map_fn(f, tf.transpose(tf.concat(0, [optimal, p1, p2]))) </code></pre> <p>First concatenate along <code>dim 0</code>, then transpose it, so that row ...
python|machine-learning|tensorflow
1
352,060
42,067,429
access elements from array of arrays, call function to execute array of arrays
<p>If I have an array like:</p> <pre><code>a = np.array([ [A(2,3 , np.array([[C(2,3)], [C(5,6)] ]))], [A(4,5 , np.array([[C(1,2)],[C(9,7)]]))] ]) </code></pre> <p>with other class instances, how can I access all the elements?</p> <p>For example,</p> <pre><code>for idx,x in np.ndenumerate...
<p><code>a</code> is 2x1 array containing 2 objects, both of class <code>A</code>:</p> <pre><code>In [162]: a Out[162]: array([[&lt;__main__.A object at 0xab20030c&gt;], [&lt;__main__.A object at 0xab20034c&gt;]], dtype=object) </code></pre> <p>I can cast the method call as function with:</p> <pre><code>def ...
python|numpy
2
352,061
41,965,458
python read file in certain format
<p>I have files with a certain format as follows:</p> <pre><code>36.1 37.1 A: Hi, how are you? 39.1 40.1 B: I am ok! </code></pre> <p>I am using <code>numpy.loadtxt()</code> to read this file with <code>dtype = np.dtype([('start', '|S1'), ('end', 'f8'),('person','|S1'),('content','|S100')])</code></p> <p>The first 3...
<p>I would recommend reading the text manually without numpy and just iterating over the lines in the file.</p> <pre><code>with open("read.txt", "r") as infile: chats = [] for i in infile: data = i.split(":") start, end, name, content = data[0].split(" ")[0], data[0].split(" ")[1], data[0].spli...
python|numpy|text
1
352,062
42,125,046
How to append data to TensorFlow tfrecords file
<p>How to append new data (e.g. pairs of images and labels) to an already existing tfrecord file?</p> <p>The class <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/lib/io/tf_record.py" rel="noreferrer">tf.python_io.TFRecordWriter</a> does not seem to have any option for that.</p> <p>Thi...
<p>According to the comments in the ticket I opened this won't be implemented, soon.</p>
python|tensorflow
9
352,063
41,887,495
Pandas, pd.to_datetime(), convert date to datetime
<p>I have a timeserie containing dates in format <code>dd/mm/yy</code> and datetime in format <code>dd/mm/yy hh:MM</code>.</p> <p>I am using <code>pd.to_datetime</code> to convert them to proper datetime format, which works fine. However, I would like to convert the datapoints in format <code>dd/mm/yy</code> to <code>...
<pre><code>from datetime import date from datetime import datetime datetime.today().strftime('%Y-%m-%d') + " 8:00" </code></pre> <p>Output:</p> <pre><code>'2017-01-27 8:00' </code></pre>
python|pandas
0
352,064
42,116,091
Pandas: Dataframe.Drop - ValueError: labels ['id'] not contained in axis
<p>Attempting to drop a column from a <code>DataFrame</code> in Pandas. <code>DataFrame</code> created from a text file.<br><br></p> <pre><code>import pandas as pd df = pd.read_csv('sample.txt') df.drop(['a'], 1, inplace=True) </code></pre> <p>However, this generates the following error: <br></p> <pre><code>ValueE...
<p>So the issue is that your "sample.txt" file doesn't actually include the data you are trying to remove. </p> <p>Your line </p> <pre><code>df.drop(['id'], 1, inplace=True) </code></pre> <p>is attepmting to take your DataFrame (which includes the data from your sample file), find the column where the value is 'id...
python|pandas
13
352,065
41,688,217
How to load a graph with tensorflow.so and c_api.h in c++ language?
<p>I am not able to find any examples about how to load a graph with <code>tensorflow.so</code> and <code>c_api.h</code> in C++. I read the <code>c_api.h</code>, however the <code>ReadBinaryProto</code> function was not in it. How can I load a graph without the <code>ReadBinaryProto</code> function?</p>
<p>If you're using C++, you might want to use the C++ API instead. The <a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/label_image" rel="noreferrer">label image example</a> would probably be a good sample to help you start.</p> <p>If you really want to use just the C API, use <a href=...
tensorflow
23
352,066
41,995,611
Replace values in a pandas column that satisfy some condition leads to SettingWithCopyWarning
<p>Let <code>dtrain</code> be of type <code>&lt;class 'pandas.core.frame.DataFrame'&gt;</code></p> <p>What is the right way to do the following?</p> <pre><code>target = dtrain.iloc[:,1] &gt; 0 dtrain.ix[target, 1] = 0 </code></pre> <p>I get the warning: </p> <blockquote> <p>/opt/local/Library/Frameworks/Python.fr...
<p>I think first can simplify code from:</p> <pre><code>dtrain = d.loc[(d.yyyy &lt; 2005) &amp; (d.yyyy &gt;= 1995),:] </code></pre> <p>to:</p> <pre><code>dtrain = d[(d.yyyy &lt; 2005) &amp; (d.yyyy &gt;= 1995)] </code></pre> <p>it is called <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean...
python|python-2.7|pandas
1
352,067
42,126,858
Numpy functions clobber my inherited datatype
<p>Say I have a class <code>ndarray_plus</code> that inherits from <code>numpy.ndarray</code> and adds some extra functionality. Sometimes I pass it to numpy functions like <code>np.sum</code> and get back an object of type <code>ndarray_plus</code>, as expected.</p> <p>Other times, numpy functions that I pass my enha...
<p>The defined and guaranteed behaviour of <code>asarray</code> is to convert your subclass instance back to base class</p> <pre><code>help on function asarray in numpy: numpy.asarray = asarray(a, dtype=None, order=None) Convert the input to an array. Parameters ---------- a : array_like Input data, in any form ...
python|numpy|inheritance
1
352,068
41,774,047
Using numpy to square value gives negative number
<p>I'm trying to use numpy to element-wise square an array. I've noticed that some of the values appear as negative numbers. The squared value isn't near the max int limit. Does anyone know why this is happening and how I could fix it? I'd rather avoid using a for loop to square an array element-wise, since my data set...
<p>This is because NumPy doesn't check for integer overflow - likely because that would slow down every integer operation, and NumPy is designed with efficiency in mind. So when you have an array of 32-bit integers and your result does not fit in 32 bits, it is still interpreted as 32-bit integer, giving you the strang...
python|numpy
27
352,069
41,859,824
ufunc 'add' did not contain loop with signature matching type dtype ('S32') ('S32') ('S32')
<p>I'm trying to run someone's script for some simulations I've made to try plotting some histograms, but when I do I always get the error message mentioned above. I have no idea what's gone wrong.</p> <p>Here's the complete traceback error I get:</p> <pre class="lang-none prettyprint-override"><code>File &quot;AVAnaly...
<p>It seems like <code>line[0]</code>, <code>line[1]</code>, <code>line[2]</code>, <code>line[3]</code> are elements of <code>dist_hist</code>. <code>dict_hist</code> is a <code>numpy.ndarray</code>. The elements of <code>dict_hist</code> has a numeric type (like <code>np.float64</code>) (based on calculations from you...
python|numpy
29
352,070
8,071,382
Points left out when nearby in scipy.spatial.Delaunay
<p>I am noticing an unexplained behaviour when comparing scipy's (0.9.0) and matplotlib's (1.0.1) Delaunay triangulation routines. My points are UTM coordinates stored in <code>numpy.array([[easting, northing], [easting, northing], [easting, northing]])</code>. Scipy's edges are missing some of my points, while matplot...
<p>This behavior of <code>scipy.spatial.Delaunay</code> might be connected with the impresicion of the floating point arithmetic. </p> <p>As you may know, <code>scipy.spatial.Delaunay</code> uses C <code>qhull</code> library to calculate Delaunay triangulation. <code>Qhull</code>, in its turn, is the implementation of...
python|numpy|matplotlib|scipy|delaunay
6
352,071
7,761,393
how to modify a 2D numpy array at specific locations without a loop?
<p>I have a 2D numpy array and I have a arrays of rows and columns which should be set to a particular value. Lets consider the following example</p> <pre><code> a = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) </code></pre> <p>I want to modify entries at rows [0,2] and columns [1,2]. This should ...
<p>Adding to what others have said, you can modify these elements using fancy indexing as follows:</p> <pre><code>In [39]: rows = [0,1] In [40]: cols = [2,2] In [41]: a = np.arange(1,10).reshape((3,3)) In [42]: a[rows,cols] = 0 In [43]: a Out[43]: array([[1, 2, 0], [4, 5, 0], [7, 8, 9]]) </code></pr...
python|numpy
31
352,072
37,934,023
How to use GeoPandas Spatial Index with lines?
<p>I am trying to find the nearest line to a bunch of points (about 24 billion points, 4 million lines). The points exist in one GeoDataFrame, while the lines exist in another. I tried to follow this: <a href="https://github.com/geopandas/geopandas/issues/140" rel="nofollow">https://github.com/geopandas/geopandas/issue...
<p>Your question is prefaced with the context that you're trying to perform a nearest neighbor query, but your question itself asks about what's going on in that geopandas intersection code block. I'll try to address your question rather than its preface, as they seem to be at odds. It looks like your intersection code...
python-3.x|geopandas
3
352,073
37,984,736
Pandas - return a dataframe after groupby
<p>I have a Pandas <code>df</code>:</p> <pre><code>Name No A 1 A 2 B 2 B 2 B 3 </code></pre> <p>I want to group by column <code>Name</code>, sum column <code>No</code> and then return a 2-column dataframe like this:</p> <pre><code>Name No A 3 B 7 </code></pre> <p>I tr...
<p>Add parameter <code>as_index=False</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="noreferrer"><code>groupby</code></a>:</p> <pre><code>print (df.groupby(['Name'], as_index=False)['No'].sum()) Name No 0 A 3 1 B 7 </code></pre> <p>Or call <a ...
python|pandas|dataframe|group-by
12
352,074
37,768,481
Convert dataframe to dictionary in Python
<p>I have a csv file that I converted into dataframe using Pandas. Here's the dataframe:</p> <pre><code>Customer ProductID Count John 1 50 John 2 45 Mary 1 75 Mary 2 10 Mary 5 15 </code></pre> <p>I need an output in the form of a dictionary that looks like ...
<p>IIUC you can use:</p> <pre><code>d = df.groupby('ProductID').apply(lambda x: dict(zip(x.Customer, x.Count))) .reset_index(name='Count') .to_dict(orient='records') print (d) [{'ProductID': 1, 'Count': {'John': 50, 'Mary': 75}}, {'ProductID': 2, 'Count': {'John': 45, 'Mary': 10}}, {'ProductID': 5, 'C...
python|dictionary|pandas|dataframe
4
352,075
37,844,522
Change dataframe row names
<p>I have a df which looks like:</p> <pre><code>BBG.LON.123.S_CAR_ADJ_DPS 343.94325 BBG.LON.436.S_CAR_ADJ_DPS 236.51530 </code></pre> <p>I am trying to rename the row names (removing the '_CAR_ADJ_DPS' element of each row name and rename the column 'id' so my resulting df looks like:</p> <pre><code> id ...
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow"><code>str.split</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#changes-to-rename" rel="nofollow"><code>rename_axis</code></a> (new in <code>pandas</code>...
python|pandas|dataframe|split|rename
3
352,076
37,674,014
TypeError while template matching in opencv python
<p>Part of my code is :</p> <pre><code>import pyscreenshot as ImageGrab img=ImageGrab.grab() img = img.load() img = np.array(img) template = cv2.imread('s2_5.jpg',0) res = cv2.matchTemplate(img,template,cv2.TM_CCOEFF) </code></pre> <p>I'm getting the following error message:</p> <pre><code>Traceback (most recent cal...
<p>You get that error because <code>img</code> and <code>template</code> are not of the same type, and more importantly, as the error messages says, <code>img</code>'s type is not supported by <a href="http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_template_matching/py_template_matchi...
python|opencv|numpy|typeerror|template-matching
1
352,077
37,704,068
Linking customers with suppliers with given choice
<p>I have an e-commerce application and the logic is simplified as below:</p> <p>There are 7 colleges with one seat each and there are 4 students who are interested in getting admission.</p> <p>Here is how to allocate seats...</p> <p>Akbar will get admission in college 324 because that is his first choice and there ...
<pre><code>select name,id from students,college, (case when first_pref,second_pref,third_pref is not null then mypref (case first_pref,second_pref,third_pref == null end) else null end) as mypref; </code></pre>
mysql|sql|pandas
1
352,078
37,794,352
How to get rows of a tsv file with common values in one of the columns using pandas?
<p>I have a tsv (tab separated) file with data like this:</p> <pre><code>1 102 apple 2 102 orange 3 103 grapes 4 103 banana 5 103 carrot </code></pre> <p>I want to get the rows of the file which have common values in the second field. And, then I want to perform operations on individual elements of each group. So I a...
<p>Would be helpful to see the output of <code>df.info()</code> after <code>pd.read_csv()</code>. In any case, you should probably do </p> <pre><code>pd.read_csv(file, sep='\t', header=None) </code></pre> <p>and then set the columns using </p> <pre><code>df.columns = ['A', 'B', 'C'] </code></pre> <p>or do the same ...
python|python-2.7|csv|pandas
2
352,079
38,040,206
Getting relative frequencies for a categorical variable (filtered on a count)?
<p>I've got a DataFrame of student test results, where the two columns that interest me are <code>country</code> and <code>result</code>, as in:</p> <pre><code>country result FR Pass FR Fail US Pass US Pass DK Fail DK Fail SE Pass ... ... </code></pre> ...
<p>You can use groupby.agg. First I created a random dataset:</p> <pre><code>import numpy as np np.random.seed(0) countries = ["FR", "US", "DK", "SE", "NL"] df = pd.DataFrame({"country": np.random.choice(countries, 1000), "result": np.random.choice(["Pass", "Fail"], 1000)}) </code></pre> <p>It has 1000 rows with coun...
python|pandas|dataframe
3
352,080
37,945,338
SQLAlchemy: query is giving error while passing integer parameter
<p>I am using SQLAchemy and python to dynamically run SQL query. But it is giving the error.</p> <p>This is my command to run the query:</p> <pre><code>data = engine.execute(m_query, week=Cohort_week, metric=metric, p1=val1, p2=val2).fetchall() </code></pre> <p>here Cohort_week, val1,val2 are integers and metric is ...
<p>It looks like you want to compare the values in the column <code>pdp_views</code> with <code>p1</code> and <code>p2</code> but what you're actually doing is comparing the string <code>'pdp_views'</code> with <code>p1</code> and <code>p2</code>, which have incompatible types.</p> <p>You should build the query dynami...
python|sql|pandas|sqlalchemy|flask-sqlalchemy
0
352,081
37,932,858
how to find dependence between 2 column in df using python
<p>I have data</p> <pre><code>city inc pop New-York 29343,00 8683,00 Moscow 25896,00 17496,00 Boston 21785,00 15063,00 Berlin 20000,00 70453,00 London 44057,00 57398,00 Rome 24000,00 104831,00 </code></pre> <p>I need to find how <code>inc</code> dependence from <code>pop</code>. I try to pl...
<p>By default, the plot <code>kind</code> parameter is line. For exploratory data analysis, it is often better to start with scatter plots. </p> <pre><code>df.plot(x='inc', y='pop', kind='scatter') </code></pre>
python|pandas|matplotlib
1
352,082
37,981,536
tensorflow.python.framework.errors.OutOfRangeError:
<p>Hi I am trying to run a conv. neural network addapted from MINST2 tutorial in tensorflow. I am having the following error, but i am not sure what is going on:</p> <pre><code>W tensorflow/core/framework/op_kernel.cc:909] Invalid argument: Shape mismatch in tuple component 0. Expected [784], got [6272] W tensorflow/...
<p>I had similar problems in the past, and it was due to that I was storing and reading the data in incorrect data types. For example, I had casted the data first as type float when converting original png data to tfrecords. Then when I read the data out from tfrecords, I once again casted it as float (assuming the dat...
python-2.7|tensorflow|conv-neural-network
2
352,083
37,719,889
How to form a matrix from submatrices?
<p>Let's say that I have these 4 submatrices:</p> <pre><code>print(A[0]) print(A[1]) print(A[2]) print(A[3]) [[ 0. 1. 2.] [ 6. 7. 8.] [ 12. 13. 14.]] [[ 3. 4. 5.] [ 9. 10. 11.] [ 15. 16. 17.]] [[ 18. 19. 20.] [ 24. 25. 26.] [ 30. 31. 32.]] [[ 21. 22. 23.] [ 27. 28. 29.] [ 33. ...
<p>With <code>A</code> as the input array containing those sub-matrices, you could use some <code>reshaping</code> and permute dimensions with <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.transpose.html" rel="nofollow"><code>np.transpose</code></a>, like so -</p> <pre><code>A.reshape(2,2,3...
python|arrays|numpy|matrix|vector
3
352,084
37,693,119
Conduct DBSCAN on radian distance matrix with sklearn?
<p>I wish to conduct clustering on several timestamps(in minutes). So what i've done so far is:</p> <p>1) Convert points to radian</p> <pre><code>#points containing time value in minutes points = [100, 200, 600, 659, 700] def convert_to_radian(x): return((x / (24 * 60)) * 2 * pi) rad_function = np.vectorize(con...
<p>Okay so after much digging i realized that i could simply just set DBSCAN metric to 'precomputed', use the <code>.fit()</code> method and pass in my distance matrix. For those that are interested here is the source:</p> <pre><code>import numpy as np from math import pi from sklearn.cluster import DBSCAN #points co...
python|numpy|scipy|scikit-learn|data-mining
5
352,085
37,883,776
array assignment using slicing
<p>When I was using array assignment using slicing, there is some thing strange happened. The source code is below:</p> <pre><code>import numpy as np a = np.array([1,2,3,4]).reshape(2,2) b = np.array([5,6,7,8]).reshape(2,2) print(id(a)) print(id(b)) b = a[:] b[1,1] = 10 print(b is a) print(id(a)) print(id(b)) print(a)...
<p>I think you might have an issue with referencing (b=a[:]). Here is a previous answer that might help: </p> <p><a href="https://stackoverflow.com/questions/4588100/python-objects-confusion-a-b-modify-b-and-a-changes">Python objects confusion: a=b, modify b and a changes!</a></p>
python|arrays|numpy
1
352,086
37,892,784
Using Keras & Tensorflow with AMD GPU
<p>I'm starting to learn Keras, which I believe is a layer on top of Tensorflow and Theano. However, I only have access to AMD GPUs such as the AMD R9 280X.</p> <p>How can I setup my Python environment such that I can make use of my AMD GPUs through Keras/Tensorflow support for OpenCL?</p> <p>I'm running on OSX.</p>
<p>I'm writing an OpenCL 1.2 backend for Tensorflow at <a href="https://github.com/hughperkins/tensorflow-cl" rel="noreferrer">https://github.com/hughperkins/tensorflow-cl</a></p> <p>This fork of tensorflow for OpenCL has the following characteristics:</p> <ul> <li>it targets any/all OpenCL 1.2 devices. It doesnt ne...
python|python-2.7|opencl|tensorflow|keras
68
352,087
38,025,162
word2vec_basic not working (Tensorflow)
<p>I am new to word-embedding and Tensorflow. I am working on a project where I need to apply <strong>word2vec</strong> to health data.<br> I used the code for Tensorflow website (<a href="http://i.stack.imgur.com/1w5GS.png" rel="nofollow"><code>word2vec_basic.py</code></a>). I modified a little this code to make it re...
<p>If the vocabulary size is less than default maximum (50000), you should modify the number.</p> <p>At the last of step 2, let's modify vocabulary_size to actual dictionary size.</p> <pre><code>data, count, dictionary, reverse_dictionary = build_dataset(words) del words # Hint to reduce memory. print('Most common w...
tensorflow|word2vec
1
352,088
31,400,769
bounding box of numpy array
<p>Suppose you have a 2D numpy array with some random values and surrounding zeros.</p> <p>Example "tilted rectangle":</p> <pre><code>import numpy as np from skimage import transform img1 = np.zeros((100,100)) img1[25:75,25:75] = 1. img2 = transform.rotate(img1, 45) </code></pre> <p>Now I want to find the smallest ...
<p>You can roughly halve the execution time by using <code>np.any</code> to reduce the rows and columns that contain non-zero values to 1D vectors, rather than finding the indices of all non-zero values using <code>np.where</code>:</p> <pre><code>def bbox1(img): a = np.where(img != 0) bbox = np.min(a[0]), np.m...
python|arrays|numpy|transformation
93
352,089
31,674,557
How to append rows in a pandas dataframe in a for loop?
<p>I have the following for loop:</p> <pre><code>for i in links: data = urllib2.urlopen(str(i)).read() data = json.loads(data) data = pd.DataFrame(data.items()) data = data.transpose() data.columns = data.iloc[0] data = data.drop(data.index[[0]]) </code></pre> <p>Each dataframe so create...
<p>Suppose your data looks like this:</p> <pre><code>import pandas as pd import numpy as np np.random.seed(2015) df = pd.DataFrame([]) for i in range(5): data = dict(zip(np.random.choice(10, replace=False, size=5), np.random.randint(10, size=5))) data = pd.DataFrame(data.items()) data =...
python|for-loop|pandas|dataframe
106
352,090
31,591,241
What does (numpy) __array_wrap__ do?
<p>I am diving into the SciPy LinAlg module for the first time, and I saw this function:</p> <pre><code>def _makearray(a): new = asarray(a) wrap = getattr(a, "__array_prepare__", new.__array_wrap__) return new, wrap </code></pre> <p><strong>What does <code>__array_wrap__</code> do exactly?</strong> I foun...
<p><code>np.ma.masked_array.__array_wrap__</code> is an example of a array subclass that updates the metadata (the <code>mask</code>).</p> <pre><code>File: /usr/lib/python3/dist-packages/numpy/ma/core.py Definition: np.ma.masked_array.__array_wrap__(self, obj, context=None) Source: def __array_wrap__(self,...
python|numpy
6
352,091
31,360,578
pandas two dataframes, some sort of merge
<p>I have two dataframes like this:</p> <pre><code>df['one'] = [1,2,3,4,5] df['two'] = [nan, 15, nan, 22, nan] </code></pre> <p>I need some sort of join or merge which will give me dataframe like this:</p> <pre><code>df['result'] = [1,15,3,22,5] </code></pre> <p>any ideas?</p>
<p>You can use the pandas method <code>combine_first()</code> to fill the missing values from a DataFrame or Series with values from another; in this case, you want to fill the missing values in <code>df['two']</code> with the corresponding values in <code>df['one']</code>:</p> <pre><code>In [342]: df['result']= df['t...
python|numpy|pandas
2
352,092
31,431,553
sort pandas value_counts() primarily by descending counts and secondarily by ascending values
<p>When applying value_counts() to a series in pandas, by default the counts are sorted in descending order, however the values are not sorted within each count.</p> <p>How can i have the values within each identical count sorted in ascending order?</p> <pre><code>apples 5 peaches 5 bananas 3 carrots 3 apric...
<p>The output of value_counts is a series itself (just like the input), so you have available all of the standard sorting options as with any series. For example:</p> <pre><code>df = pd.DataFrame({ 'fruit':['apples']*5 + ['peaches']*5 + ['bananas']*3 + ['carrots']*3 + ['apricots'] }) df....
python-3.x|pandas
4
352,093
31,473,457
Converting query results into DataFrame in python
<p>I am trying to perform manipulation on the result from a query using psycog2. Thus I have to covert result into pandas DataFrame. But when i use the following code and print, only the columns name are printed not the rows. I used 'pd.DataFrame.from_records' too but that did not work.</p> <pre><code>import psycopg2 ...
<p>Maybe not directly an answer on your question, but you should use <code>read_sql_query</code> for this instead doing the fetchall and wrap in DataFrame yourself. This would look like:</p> <pre><code>conn = psycopg2.connect(...) rows = pd.read_sql_query(query, conn) </code></pre> <p>instead of all your code above.<...
python|pandas|dataframe|psycopg2
11
352,094
64,250,373
Keras 'plot_model' shows wrong graph for nested models (Autoencoder)
<p>When I create an autoencoder architecture with multiple inputs and outputs, the <code>plot_model</code> graph does not show up as expected (problems highlighted in red).</p> <p>I assume the first issue occurs because I use <code>encoder.inputs</code> for the autoencoder. However, creating new input layers for the au...
<p>I was able to prevent the first problem by adding two input layers to the autoencoder.</p> <p>The second problem (multiple outputs just connecting to one input) seems to be a known bug: <a href="https://github.com/tensorflow/tensorflow/issues/42101" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/...
tensorflow|keras|tensorflow2.0|keras-layer|autoencoder
1
352,095
64,197,711
Iterating through a data frame and grouping values in a range
<p>I have a python data frame of weekly data like this :</p> <pre><code>Week Val 1 11 2 11 3 11 4 11 5 9 6 9 7 9 8 9 </code></pre> <p>I would like create an output table like this:</p> <pre><code>Week 1 Week 2 Val 1 4 11 5 8 9 </code></pre> <p>Apologies, I am quite new to pyt...
<p>You want to groupby the consecutive blocks of <code>Val</code>. So you can use <code>cumsum</code> on the non-zero differences to get the block:</p> <pre><code>blocks = df['Val'].ne(df['Val'].shift(1)).cumsum() (df.groupby(blocks, as_index=False) .agg(Week1=('Week','min'), Week2=('Week','max'), Val=('Val', 'firs...
python-3.x|pandas
0
352,096
64,281,042
I have installed pipwin but having trouble in installing pyaudio,showing pipwin is not recognizable
<p>PS C:\Users\adity\Desktop\Python project&gt; pip install pipwin WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip. Please see <a href="https://github.com/pypa/pip/issues/5599" rel="nofollow noreferrer">https://github.com/pypa/pip/issues/5599</a> for advice on fixing th...
<p>It seems to be an error with the path. what happens when you type <code>where pipwin</code> in cmd? If the output is something like this</p> <pre><code>INFO: Could not find files for the given pattern(s). </code></pre> <p>then try adding pipwin to PATH or reinstall pipwin.</p> <pre><code>pip install pipwin </code></...
numpy|pip|speech-recognition|python-3.8|pyaudio
0
352,097
64,382,531
Collect the column name whose value is True for each row in dataframe
<p>I have a dataframe which looks like this:</p> <pre><code>**col_A col_B col_C** False True False True False False False False True False False False </code></pre> <p>I need to collect the column name whose value is True for each row and create another dataframe:</p> <pre><code>**col** col_B col_A col_C nan </code><...
<p>Here you go with <code>idxmax</code> and <code>where</code>:</p> <pre><code>df.idxmax(1).where(df.any(1)) </code></pre> <p>Output:</p> <pre><code>0 col_B 1 col_A 2 col_C 3 NaN dtype: object </code></pre>
python|python-3.x|pandas|dataframe|data-science
1
352,098
64,451,911
Creating new dataframe from preexisting dataframe using Python
<p>I have a large file, df1, that I wish to extract some data from its cells and then create a new file, df2 with a new column name and datetime column:</p> <p>df</p> <pre><code> A B C D E 1 2 3 4 5 </code></pre> <p>Desired output:</p> <pre><code> Date Value 1/1/202...
<p>Assuming <code>Date</code> is a constant value you need to add, you can do this:</p> <pre><code>In [1393]: df Out[1393]: A B C D E 0 1 2 3 4 5 In [1395]: x = df.at[0, 'C'] # Pick 1st row's column C In [1396]: y = '1/1/2020' In [1398]: df = pd.DataFrame({'Date':[y], 'Value':[x]}) In [1399]: df Out[13...
python|pandas|loops
1
352,099
64,416,964
The CLI for chat-bot conversation is not coming after running it as a docker image
<p>I have crated a chat-bot using python 3.6 and TensorFlow 1.15. And created the Command line utility for testing in local environment.</p> <p>The command line utility works fine without docker as shown in the below image. <a href="https://i.stack.imgur.com/AhVH1.png" rel="nofollow noreferrer"><img src="https://i.stac...
<p>Your dockerfile seems fine. for the interactive mode for your chatbot conversation you need to add &quot;-i&quot; flag in your docker run command.</p> <pre><code>docker run -i &lt;image_name&gt; </code></pre>
python|docker|tensorflow|dockerfile|chatbot
1