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
9,400
68,159,213
Python/Pandas dataframe: Finish writing to file when program stops
<p>I am appending data to dataframes in python in a parallel fashion for multiple CSV-files using the to_csv() function for pandas dataframes.</p> <p>However when I stop the program while it runs, some files are completely emptied. When I stop the program unexpectedly, I want python to either finish writing to the file...
<pre><code>csv.flush() csv.close() </code></pre> <p>The flush() method in Python file handling clears the internal buffer of the file. In Python, files are automatically flushed while closing them. However, a programmer can flush a file before closing it by using the flush() method.</p>
python|pandas|file
0
9,401
68,359,147
Obtaining total seconds from a datetime.time object
<p>I have a datetime.time object as 02:00:00 i would like to convert it to the total seconds which should be 7200 seconds.</p>
<p>You can combine the time with a reference date to get a datetime object. If you then subtract that reference date, you get a timedelta object, from which you can take the <code>total_seconds</code>:</p> <pre><code>from datetime import datetime, time t = time(2,0,0) ts = (datetime.combine(datetime.min, t) - datetim...
python|pandas|datetime|timedelta
3
9,402
68,091,936
Grouping Nearby Contours/Bounding Rectangles
<p>I have an image containing obscure rectangular shapes: <a href="https://i.stack.imgur.com/0JTGP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0JTGP.png" alt="enter image description here" /></a></p> <p>Using opencv I would like to group nearby rectangles to have an expected output as: <a href="h...
<p>A thin vertical kernel should do what you want. Just make it taller than the maximum of the minimum 1/2 gaps over all objects you want to connect. Looks like about 65 pixels should work. Here is the morphology close result in Python/OpenCV that seems to connect the parts you want.</p> <p>Input:</p> <p><a href="https...
python|numpy|opencv|image-processing
2
9,403
59,077,221
Merging DFs from two different lists in python
<p>There are two lists where elements are DFs and having <code>datetimeindex</code>:</p> <pre><code>lst_1 = [ df1, df2, df3, df4] #columns are same here 'price' lst_2 = [df1, df2, df3, df4] #columns are same here 'quantity' </code></pre> <p>I am doing it with one by one using the pandas merge function. I tried...
<p>Consider elementwise looping with <code>zip</code> which can be handled in a list comprehension.</p> <pre><code># DATES AS INDEX final_lst = [pd.concat(i, j, axis=1) for i, j in zip(lst_1, lst_2)] # DATES AS COLUMN final_lst = [pd.merge(i, j, on='Dates') for i, j in zip(lst_1, lst_2)] </code></pre>
python|pandas|dataframe|merge
2
9,404
59,319,729
Finding min, max, avg in Pandas, Python for all rows with the same first column
<p>Is it possible to find minimum, maximum and average value of all data with a same first column?</p> <p>For example, for first column <code>1_204192587</code>:</p> <ol> <li><p>take into account all rows and columns from 4 to n</p> </li> <li><p>find min, max and avg of all entries in columns 4+ and all rows with <code...
<p>You can use the below:</p> <pre class="lang-py prettyprint-override"><code>df.loc[4:].describe() </code></pre> <p><code>df</code> is your dataframe <br/> <code>[4:]</code> chooses the 5th row and on <br/> <code>.describe()</code> gives you a statistical summary (avg, mean ...)</p> <p>You can also add <code>.trans...
python|pandas|max|average|min
2
9,405
59,193,132
Time difference between two columns in Pandas
<p>How can I subtract the time between two columns and convert it to minutes </p> <pre><code> Date Time Ordered Time Delivered 0 1/11/19 9:25:00 am 10:58:00 am 1 1/11/19 10:16:00 am 11:13:00 am 2 1/11/19 10:25:00 am 10:45:00 am 3 1/11/19 10:45:00 am 11:12:00 am 4 1/11/19 11:11:00 am 1...
<p>Convert both time columns to datetimes, get difference, convert to seconds by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.total_seconds.html" rel="noreferrer"><code>Series.dt.total_seconds</code></a> and then to minutes by division by <code>60</code>:</p> <pre><code>df['diff'...
pandas|numpy|dataframe
5
9,406
45,109,115
compare all couples of numeric columns of a dataframe
<p>I have the following csv file:</p> <blockquote> <pre><code>C1,C2,C3,C4,C5,C6,C7 0,1,1,1,1,1,1 1,1,1,1,1,1,1 0,1,1,1,0,0,1 0,1,0,1,0,0,1 0,1,1,1,1,1,1 1,1,1,1,1,1,1 </code></pre> </blockquote> <p>I would like to create a dataframe comparing columns pairs. I would like to count the number of times each pair of colum...
<p>If the data frame contains only 1 and 0, you can use matrix multiplication <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dot.html" rel="nofollow noreferrer">dot</a>:</p> <pre><code>df = pd.read_csv("/path/to/csvfile") df.T.dot(df) </code></pre> <p><a href="https://i.stack.imgur.c...
python|pandas|dataframe
4
9,407
44,931,216
TensorFlow image reading queue empty
<p>I'm trying to use the pipeline for reading images to the CNN. I used <code>string_input_producer()</code> to obtain the queue of file names, but it seems to hang there without doing anything. Below is my code, please give me some advise of how to make it work.</p> <pre><code>def read_image_file(filename_queue, labe...
<p>Your code is not completely self-contained as the <code>get_label</code> method is not defined.</p> <p>But it is very likely that the issue you have comes from these lines in the <code>read_image_file</code> method:</p> <pre><code>with tf.Session() as sess: label = getLabel(labels, key.eval()) </code></pre> <...
machine-learning|tensorflow|computer-vision
0
9,408
45,020,672
Convert PyQt5 QPixmap to numpy ndarray
<p>I have pixmap:</p> <pre><code>pixmap = self._screen.grabWindow(0, self._x, self._y, self._width, self._height) </code></pre> <p>I want to convert it to OpenCV format. I tried to convert it to <code>numpy.ndarray</code> as described <a href="https://...
<p>I got numpy array using this code:</p> <pre><code>channels_count = 4 pixmap = self._screen.grabWindow(0, self._x, self._y, self._width, self._height) image = pixmap.toImage() s = image.bits().asstring(self._width * self._height * channels_count) arr = np.fromstring(s, dtype=np.uint8).reshape((self._height, self._wi...
python|numpy|pyqt|pyqt5|qpixmap
7
9,409
44,875,888
Running a for loop through 2 arrays of different lengths and index manipulation
<p>I need to run a for loop through 2 arrays of different lengths. One array is 8760 by 1 and the other is 10 by 1. If a value in the short array is equal to to the index of a value in the long array, I don't want to change anything. If the index of a value in the long array isn't equal to a value in the short array, I...
<p><strong>Main principle</strong></p> <p>When you need a <code>for</code> loop to walk across the indices of an array, use a "counted" loop-- a loop that iterates across a set of integers. Use <code>for index in range(len(</code>your list<code>)</code>.</p> <p><strong>Your specific problem</strong></p> <p>Given you...
python|arrays|numpy|for-loop|indexing
1
9,410
56,981,256
Python: append() and extend()
<p>I have a .txt file of 3 million rows. The file contains data that looks like this:</p> <pre><code># RSYNC: 0 1 1 0 512 0 #$SOA 5m localhost. hostmaster.localhost. 1906022338 1h 10m 5d 1s # random_number_ofspaces_before_this text $TTL 60s #more random information :127.0.1.2:https://www.spamhaus.org/query/domain/$ te...
<p>The likely source of your problem is a missing comma.</p> <p>This:</p> <pre><code>df = pd.DataFrame(rows, columns=[ 'domain_name', 'parsed_code', 'raw_spamhaus_return_code']) </code></pre> <p>is not the same as:</p> <pre><code>df = pd.DataFrame(rows, columns=[ 'domain_name', "parsed_code" 'raw_spamhaus_r...
python|regex|pandas
5
9,411
57,181,569
Random colors by default in matplotlib
<p>I had a look at Kaggle's <a href="https://www.kaggle.com/residentmario/univariate-plotting-with-pandas" rel="nofollow noreferrer">univariate-plotting-with-pandas</a>. There's this line which generates bar graph. </p> <p><code>reviews['province'].value_counts().head(10).plot.bar()</code></p> <p>I don't see any colo...
<p>In seaborn is it not problem:</p> <pre><code>import seaborn as sns sns.countplot(x='province', data=reviews) </code></pre> <p>In matplotlib are not spaces, but possible with convert values to one row DataFrame:</p> <pre><code>reviews['province'].value_counts().head(10).to_frame(0).T.plot.bar() </code></pre> <p>...
python|pandas|matplotlib
4
9,412
57,065,878
Split pandas column and create new columns that count the split values
<p>I have a goofy data where one column contains multiple values slammed together with a comma:</p> <pre class="lang-py prettyprint-override"><code>In [62]: df = pd.DataFrame({'U': ['foo', 'bar', 'baz'], 'V': ['a,b,a,c,d', 'a,b,c', 'd,e']}) In [63]: df ...
<p>This is <code>str.get_dummies</code></p> <pre><code>pd.concat([df,df.pop('V').str.split(',',expand=True).stack().str.get_dummies().sum(level=0)],1) Out[602]: U a b c d e 0 foo 2 1 1 1 0 1 bar 1 1 1 0 0 2 baz 0 0 0 1 1 </code></pre>
python|pandas
5
9,413
57,257,620
How can I loop the columns of a dataframe and then calling them as df.col without having python think col is a method?
<p>I'm trying to loop all the columns of a dataframe but I can't call them inside the loop as df.col, apparently it reads col as a method and gives me an error because no such method exists. </p> <pre><code>for bin in bins: for col in app_train.columns: if app_train[col].isnull().any(): app_tr...
<p>The for loop are not needed since pandas can deal with this kind of operation:</p> <pre><code>df.fillna(df.groupby(['YEARS_BINNED']).transform('mean'),inplace=True) </code></pre> <p>This line will fill the NaN value of your dataframe with the mean of the respective column grouped by <code>YEARS_BINNED</code></p>
python-3.x|pandas|loops
0
9,414
57,118,106
ValueError: Input contains NaN, infinity or a value too large for dtype('float32'). Why?
<p>I have gone through all the similar questions but none of them answer my query. I am using random forest classifier as follows:</p> <pre class="lang-py prettyprint-override"><code>from sklearn.ensemble import RandomForestClassifier clf = RandomForestClassifier(n_estimators=100, max_depth=2, random_state=0) clf.fit(...
<p><strong>Solution</strong><br/><code>X_train = X_train.fillna(X_train.mean())</code></p> <p><strong>Explanation</strong><br/> <code>np.any(np.isnan(X_train))</code> evals to <code>True</code>, therefore <code>X_train</code> contains some <code>nan</code> values. Per pandas <a href="https://pandas.pydata.org/pandas-...
python|pandas|numpy|scikit-learn|jupyter
1
9,415
57,231,943
How can I randomly shuffle the labels of a Pytorch Dataset?
<p>I am new to Pytorch, and I am having troubles with some technicalities. I have downloaded the MNIST dataset, using the following command:</p> <pre><code>train_dataset = dsets.MNIST(root='./data', train=True, transform=transforms.ToTensor(), ...
<p>If you only want to shuffle the targets, you can use <a href="https://pytorch.org/docs/stable/torchvision/datasets.html#mnist" rel="nofollow noreferrer"><code>target_transform</code></a> argument. For example:</p> <pre class="lang-py prettyprint-override"><code>train_dataset = dsets.MNIST(root='./data', ...
machine-learning|computer-vision|dataset|pytorch
2
9,416
57,062,108
Converting Items from Pandas Series to Date Time
<p>I have a Pandas Series ("timeSeries") that includes a time of day. Some of the items are blank, some are actual times (08:00; 13:00), some are indications of time (morning, early afternoon). </p> <p>As the time of day I have is New York, I would like to convert the items in the time format to London time. Using <co...
<p>Using the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/indexing.html#id3" rel="nofollow noreferrer"><code>.dt</code> accessor</a>, you can set a timezone to your value, and than convert it to another one, using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.tz_lo...
python|pandas|datetime
0
9,417
56,890,105
How to keep NaN in pivot table?
<p>Looking to preserve NaN values when changing the shape of the dataframe.</p> <p>These two questions may be related:</p> <ul> <li><a href="https://stackoverflow.com/questions/56742166/">How to preserve NaN instead of filling with zeros in pivot table?</a></li> <li><a href="https://stackoverflow.com/questions/556261...
<p>From the helpful comments the following solution meets my requirements:</p> <pre class="lang-py prettyprint-override"><code> pivot_df_2 = pd.pivot_table(df, values='B', index=['Date'], columns=['A'],aggfunc=min, dropna=False) pivot_df_2 </code></pre> <p>Values are supposed to be unique per slot so replacing the s...
python|pandas|numpy
2
9,418
46,066,685
Rename the column inside csv file
<p>Can anyone please check for me what's wrong with my renaming command. It changes nothing on the csv file. The code that i have tried below renaming header.</p> <pre><code>df = pandas.read_csv('C:/JIRA Excel File.csv') df.rename(columns=({'Custom field (Implemented Date)':'Custom field (Verified Date)'})) df.set_ind...
<p>you can call rename function with external parameter <code>inplace=True</code> </p> <pre><code>df.rename(columns={'Custom field (Implemented Date)': 'Custom field (Verified Date)'}, inplace=True) </code></pre> <p>For more see <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rename.ht...
python|pandas
4
9,419
46,044,618
Count of values between other values in a pandas DataFrame
<p>I have a column of a pandas DataFrame that looks like this:</p> <pre><code>1 False 2 False 3 False 4 True 5 True 6 False 7 False 8 False 9 False 10 False 11 True 12 False </code></pre> <p>I would like to get the count of False between the True....
<p>Group by the cumulative sum of itself and then count the <code>False</code> with <code>sum</code>:</p> <pre><code>s = pd.Series([False, False, False, True, True, False, False, False, False, False, True, False]) (~s).groupby(s.cumsum()).sum() #0 3.0 #1 0.0 #2 5.0 #3 1.0 #dtype: float64 </code></pre>
python|pandas
5
9,420
45,971,533
Slicing array returns strange shape
<p>Suppose I do the following in Ipython:</p> <pre><code>import numpy as np test = np.zeros([3,2]) test test.shape test[:,0] test[:,0].shape </code></pre> <p>The results will be:</p> <pre><code>array([[ 0., 0.], [ 0., 0.], [ 0., 0.]]) (3,2) array([ 0., 0., 0.]) (3,) </code></pre> <p>Why is the la...
<p>I use a different array for visualization:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; test = np.arange(6).reshape(3, 2) &gt;&gt;&gt; test array([[0, 1], [2, 3], [4, 5]]) </code></pre> <p>Slicing like this:</p> <pre><code>&gt;&gt;&gt; test[:,0] array([0, 2, 4]) </code></pre> <p>tell...
python|python-3.x|numpy|slice|reshape
2
9,421
23,026,037
Pandas div using index
<p>I am sometimes struggling a bit to understand pandas datastructures and it seems to be the case again. Basically, I've got:</p> <ul> <li>1 pivot table, major axis being a serial number</li> <li>a Serie using the same index</li> </ul> <p>I would like to divide each column of my pivot table by the value in the Serie...
<p>You say "using the same index", but they're not the same: <code>pt</code> has a multiindex, and <code>serie</code> only an index:</p> <pre><code>&gt;&gt;&gt; pt.index MultiIndex(levels=[[u'123', u'456'], [1, 2, 4]], labels=[[0, 0, 1], [0, 2, 1]], names=[u'A', u'B']) </code></pre> <p>And you h...
python|pandas
1
9,422
35,611,786
Select one cell when pandas DataFrame has hierarchical index
<p>I would expect to be able to do </p> <p><code>dat.loc['label_row1', 'label_row2', 'label_col']</code></p> <p>However, it does not work and require </p> <p><code>dat.loc['label_row1', 'label_row2'].loc['label_col']</code></p> <p>To me, this is rather unintuitive, because when there isn't hierarchical index, I can...
<p>If your index is first sorted, you can do this which selects all countries and the year 2009:</p> <pre><code>dat.sort_index().loc[(slice(None), '2009'), :] BX.KLT.DINV.WD.GD.ZS country year China 2009 2.590357 </code></pre> <p>Here is a link to <a href="http://pan...
python|pandas
1
9,423
28,598,035
Pandas: 52 week high from yahoo or google finance
<p>Does anyone know if you can get the 52 week high in pandas from either yahoo or google finance? Thanks. </p>
<p>It is possible, please check out <a href="http://pandas.pydata.org/pandas-docs/dev/remote_data.html" rel="nofollow">pandas documentation</a>. Here's an example:</p> <pre><code>import pandas.io.data as web import datetime symbol = 'aapl' end = datetime.datetime.now() start = end - datetime.timedelta(weeks=52) df ...
python|pandas|yahoo|finance
2
9,424
50,925,783
error with DataType when training CNN
<p>I have a problem with the training of a CNN. I based it on the example that can be found at <a href="https://www.tensorflow.org/tutorials/layers" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/layers</a>. The difference between my network and the one in the example is that i am using my own data inst...
<p>Even though there are too many function calls and errors in the log, the main reason for the error can always be found in the last statement. In this case, "<strong>TypeError: Value passed to parameter 'input' has DataType uint8 not in list of allowed values: float16, bfloat16, float32, float64.</strong>"</p> <p>As...
python|tensorflow|convolutional-neural-network
3
9,425
20,485,139
Multiple AggFun in Pandas
<p>If you think about pivot tables in <code>Excel</code>, you can add additional columns and change from sum to mean to min or max. Is it possible to get the multiple values in a <code>pivot</code> in <code>Pandas</code>? </p> <p>Here is a working example (lifted from the pandas documentation):</p> <pre><code>import...
<p>You can pass a list to <code>pivot_table</code>'s <code>aggfunc</code> keyword argument:</p> <pre><code>&gt;&gt;&gt; pd.pivot_table(df, values=['D', 'E'], rows=['B'], aggfunc=[np.mean, np.sum]) mean sum D E D E B ...
python|pandas
5
9,426
9,070,306
numpy/scipy/ipython:Failed to interpret file as a pickle
<p>I have the file in following format: </p> <pre><code>0,0.104553357966 1,0.213014562052 2,0.280656379048 3,0.0654249076288 4,0.312223429689 5,0.0959008911106 6,0.114207780917 7,0.105294501195 8,0.0900673766572 9,0.23941317105 10,0.0598239513149 11,0.541701803956 12,0.093929580526 </code></pre> <p>I want to plot the...
<p>The <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.load.html" rel="noreferrer"><code>numpy.load</code></a> routine is for loading pickled <code>.npy</code> or <code>.npz</code> binary files, which can be created using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.save.html" r...
python|numpy|matplotlib|scipy|ipython
23
9,427
66,374,254
Creating a new matrix from a matrix of index in numpy
<p>I have a 3D numpy array <code>A</code> with shape(k, l, m) and a 2D numpy array <code>B</code> with shape (k,l) with the indexes (between 0 and m-1) of particular items that I want to create a new 2D array <code>C</code> with shape (k,l), like this:</p> <pre><code>import numpy as np A = np.random.random((2,3,4)) B =...
<p>Use inbuilt routine name <code>fromfunction</code> of Numpy library. And turn your code into</p> <pre><code>C = np.fromfunction(lambda i, j: A[i, j, B[i,j]], (5, 5)) </code></pre>
python|arrays|numpy
2
9,428
66,387,970
Pandas read_csv does not separate values after comma
<p>I am trying to load some .csv data in the Jupyter notebook but for some reason, it does not separate my data but puts everything in a single column.</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt df = pd.read_csv(r'C:\Users\leonm\Documents\Fontys\Semester 4\GriefBot_Practice...
<p>If that's how your data looks in a CSV reader like Excel, then each row likely looks like one big string in a text editor.</p> <pre><code>&quot;ID,PERSON,DATE&quot; &quot;1,A. Molina,1593147221&quot; &quot;2,A. Moran, 16456&quot; &quot;3,Action Marquez,15436&quot; </code></pre> <p>You could of course do &quot;text t...
python|pandas|csv
2
9,429
57,297,569
Mapping data to ground truth list
<p>I have ground truth data in the following Python list:</p> <pre><code>ground_truth = [(A,16), (B,18), (C,36), (A,59), (C,77)] </code></pre> <p>So any value from:</p> <pre><code>0-16 gets mapped to A, 17-18 maps to B, 19-36 maps to C, 37-59 maps to A 60-77 maps to C and so on </code></pre> <p>I am trying to ma...
<p>Here's my approach:</p> <pre><code>gt = pd.DataFrame(ground_truth) # bins for cut bins = [0] + list(gt[1]) # categories cats = pd.cut(pd.Series([9,15,29,32,49,56, 69]), bins=bins, labels=False) # labels gt.loc[cats, 0] </code></pre> <p>gives</p> <pre><code>0 A 0 A 2 C 2 C 3 A 3 A 4 C Name:...
pandas
7
9,430
57,503,000
How to compare a single cell to an entire column of a dataframe in python using pandas
<p>I'm getting this error: "The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()." despite my best efforts to check the intermediate outputs (getting bools where expected, and the numbers are the correct data type I think, numpy.float64) I'm also using bit-wise operators.</p> <...
<p>I beleive the the soln is: </p> <pre><code>for i in range(len(df)): #include RT too counter = 0 counter = np.count_nonzero(((df.at[i, 'M-1 m/z'] - (df.at[i, 'M-1 m/z']/10**6)*100) &lt;= df['observed M0 m/z']) &amp; ((df.at[i, 'M-1 m/z'] + (df.at[i, 'M-1 m/z']/10**6)*100) &gt;= df['observed M0 m/z'])) df.at[i, 'M-1...
pandas|dataframe
0
9,431
57,362,679
Python - Mirror a data set
<p>I have a data set, with XYZ cooridnate values and a scalar value at each X Y Z coordinate. I am looking to mirror this on YZ plane, and then XY plane. </p> <p>I was able to do this, by manually reading everything into a list or numpy array, creating a new array for each mirror. HOwever, that is not efficient. Wonde...
<p>If you have a dataframe (from what I understand), you can <code>append</code> (multiple times) modified copies of the dataframe, changing each time one or more columns of your choosing by using <code>df.assign</code>:</p> <pre><code>df = pd.DataFrame({'scalar': [123] * 3, 'sym': 'None', 'x': np.o...
python|arrays|pandas|numpy
0
9,432
57,572,695
I have to compare data from each row of a Pandas DataFrame with data from the rest of the rows, is there a way to speed up the computation?
<p>Let's say I have a pandas DataFrame (loaded from a csv file) with this structure (the number of var and err columns is not fixed, and it varies from file to file):</p> <pre><code>var_0; var_1; var_2; 32; 9; 41; 47; 22; 41; 15; 12; 32; 3; 4; 4; 10; 9; 41; 43; 21; 45; 32; 14...
<p>Another speedup can be accomplished by replacing <code>.iloc[].values</code> as well as <code>.loc[]</code> with <code>.values[]</code>, but with <code>.loc[]</code> we have to adjust the subscript, because <code>.values</code> takes a zero-based subscript, which is different from our 1-based <code>dom_table_df.inde...
python|pandas|performance|dataframe|optimization
1
9,433
43,632,476
InvalidArgumentError on softmax in tensorflow
<p>I have the following function:</p> <pre><code>def forward_propagation(self, x): # The total number of time steps T = len(x) # During forward propagation we save all hidden states in s because need them later. # We add one additional element for the ini...
<p>The problem arises because you call <code>tf.reduce_sum</code> on the argument of <code>tf.nn.softmax</code>. As a result, the softmax function fails because a scalar is not a valid input argument. Did you mean to use <code>tf.matmul</code> instead of the combination of <code>tf.reduce_sum</code> and <code>tf.multip...
python|numpy|tensorflow
2
9,434
43,615,727
wrong exception handling in feed_dict in tensorflow
<p>I create my tensorflow graph as following:</p> <pre><code>s = tf.zeros([T+1, self.hidden_dim]) o = tf.zeros([T, self.word_dim]) a = tf.placeholder(tf.float32) b = tf.placeholder(tf.float32) c = tf.placeholder(tf.float32) d = tf.placeholder(tf.float32) dot_product = tf.reduce_sum(tf.multiply(a, b)) s_t = tf.nn.tanh(...
<p>TF complains because your variable <code>s</code> is a <code>tf.Tensor</code> (it has no problems with your 'W' variable).</p> <p>It it would not be a tensor, this part of the code <code>sess.run(s)</code> would complain with something like this: <code>Fetch argument XX has invalid type &lt;type 'YY'&gt;, must be a...
python|numpy|tensorflow
1
9,435
43,485,230
Python Pandas - Find the elements ( substring ) in the same column
<p>I have a string column ('b') and would like to get the strings which are like substring in the same column. Example, in the below dataframe column 'b' , world is a substring of helloworld and ness is a substring of greatness. I would like to get the strings world and ness in a list. Can you please suggest a solution...
<p>You can use:</p> <pre><code>from itertools import product #get unique values only b = df.b.unique() #create all combination df1 = pd.DataFrame(list(product(b, b)), columns=['a', 'b']) #filtering df1 = df1[df1.apply(lambda x: x.a in x.b, axis=1) &amp; (df1.a != df1.b)] print (df1) a b 1 world h...
python|python-2.7|pandas|dataframe
2
9,436
43,632,925
Efficient loop through pandas dataframe
<p>I have the following problem I need help with. I have 310 records in a csv file that contains some information about bugs. In another csv file I have 800 thousand records containing statistics about the bags (events that possibly led to the bugs).</p> <p>With the script below, I am trying to </p> <ol> <li>Loop thr...
<p>First of all: are you sure that your code does what you want it to do? As I see it, you keep looping over your statistics, so if you found a matching bug with bug #1, you can later overwrite the corresponding appendix to the statistics data with bug #310. It is unclear what you should be doing with statistics events...
python|performance|pandas|numpy|vectorization
1
9,437
2,231,842
Numpy with python 3.0
<p>NumPy installer can't find python path in the registry.</p> <blockquote> <p>Cannot install Python version 2.6 required, which was not found in the registry.</p> </blockquote> <p>Is there a numpy build which can be used with python 3.0?</p>
<p>Guido van Rossum (creator of Python) says he is <a href="http://neopythonic.blogspot.com/2009/11/python-in-scientific-world.html" rel="noreferrer">keen to see NumPy work in Python 3.x</a>, because it would enable many dependent libraries to move to 3.x.</p> <p><strong>Update 2010-08-05:</strong> <a href="http://www...
python|numpy|python-3.x
46
9,438
72,929,810
Manipulate string values in pandas
<p>I have a pandas dataframe with different formats for one column like this</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Name</th> <th>Values</th> </tr> </thead> <tbody> <tr> <td>First</td> <td>5-9</td> </tr> <tr> <td>Second</td> <td>7</td> </tr> <tr> <td>Third</td> <td>-</td> </tr> <tr...
<p>Let us <code>split</code> and <code>expand</code> the column then cast values to <code>float</code> and calculate <code>mean</code> along column axis:</p> <pre><code>s = df['Values'].str.split('-', expand=True) df['Values'] = s[s != ''].astype(float).mean(1).fillna(0) </code></pre> <hr /> <pre><code> Name Value...
python|pandas
3
9,439
73,072,920
Finding perimeter coordinates of a mask
<pre><code> [[ 0, 0, 0, 0, 255, 0, 0, 0, 0], [ 0, 0, 255, 255, 255, 255, 255, 0, 0], [ 0, 255, 255, 255, 255, 255, 255, 255, 0], [ 0, 255, 255, 255, 255, 255, 255, 255, 0], [255, 255, 255, 255, 255, 255, 255, 255, 255], [ 0, 255, 255, 255, 255, 255, 2...
<p>I played a bit with your problem and found a solution and I realized you could use convolutions to count the number of neighboring 255s for each cell, and then perform a filtering of points based on the appropriate values of neighbors.</p> <p>I am giving a detailed explanation below, although one part was trial and ...
python|numpy
2
9,440
73,139,560
Adding rows using timestamp
<p>I saw this code <a href="https://stackoverflow.com/questions/46074742/combine-rows-and-add-up-value-in-dataframe">combine rows and add up value in dataframe</a>,</p> <p>but I want to add the values in cells for the same day, i.e. add all data for a day. how do I modify the code to achieve this?</p>
<p>Check below code:</p> <pre><code>import pandas as pd df = pd.DataFrame({'Price':[10000,10000,10000,10000,10000,10000], 'Time':['2012.05','2012.05','2012.05','2012.06','2012.06','2012.07'], 'Type':['Q','T','Q','T','T','Q'], 'Volume':[10,20,10,20,30,10] ...
python|pandas|dataframe|for-loop|timestamp
0
9,441
72,933,196
Python Pandas Converting Dataframe to Tidy Format
<pre><code>dt = {'ID': [1, 1, 1, 1, 2, 2, 2, 2], 'Test': [‘Math’, 'Math', 'Writing', 'Writing', ‘Math’, 'Math', 'Writing', 'Writing', ‘Math’] 'Year': ['2008', '2009', '2008', '2009', '2008', ‘2009’, ‘2008’, ‘2009’], 'Fall': [15, 12, 22, 10, 12, 16, 13, 23] ‘Spring’: [1...
<p>You can try with <code>set_index</code> with <code>stack</code> + <code>unstack</code></p> <pre><code>out = (df.set_index(['ID','Test','Year']). stack().unstack(level=1). add_suffix('_Score').reset_index()) out Out[271]: Test ID Year level_2 Math_Score Writing_Score 0 1 2008 Fal...
python|pandas
0
9,442
73,127,093
Stack dataframes in Pandas vertically and horizontally
<p>I have a dataframe that looks like this:</p> <pre><code> country region region_id year doy variable_a num_pixels 0 USA Iowa 12345 2022 1 32.2 100 1 USA Iowa 12345 2022 2 12.2 100 2 USA Iowa 12345 2022 3 22.2 100 3 USA...
<p>IIUC, this should work for you:</p> <pre><code>data1 = { 'country': {0: 'USA', 1: 'USA', 2: 'USA', 3: 'USA', 4: 'USA'}, 'region': {0: ' Iowa', 1: ' Iowa', 2: ' Iowa', 3: ' Iowa', 4: ' Iowa'}, 'region_id': {0: 12345, 1: 12345, 2: 12345, 3: 12345, 4: 12345}, 'year': {0: 2022, 1: 2022, 2: 2022, 3: 2022,...
python|pandas
3
9,443
70,590,276
Shifting a value and creating a new index using pandas
<p>I have a <code>df</code></p> <pre><code> 2019 2020 2021 2022 A 10 20 30 40 </code></pre> <p>I am trying to create 2 new indexes <code>A-1</code> and <code>A-2</code> so that the output would look like this:</p> <pre><code> ...
<p>Juste use <code>loc</code> to create your new indexes</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({2019:[10], 2020:[20], 2021:[30], 2022:[40]}, index=[&quot;A&quot;]) &gt;&gt;&gt; df.loc[&quot;A-1&quot;] = df.loc[&quot;A&quot;].shift() &gt;&gt;&gt; df.loc[&quot;A-2&quot;] = df.loc[&quot;A-1&quot;].shift() &gt;&gt;...
python|pandas
1
9,444
70,631,807
Python Pandas Pivot Of Two columns (ColumnName and Value)
<p>I have a Panda dataframe that contains two columns, as well as a default index. The first columns is the intended 'Column Name' and the second column the required value for that column.</p> <pre><code> name returnattribute 0 Customer Name Customer One Name 1 Customer Code CGLOSPA 2 Customer ...
<p>In <code>df.pivot</code> when <code>index</code> parameter is not passed <code>df.index</code> is used as default. Hence, the output.</p> <ul> <li><a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferrer">From Docs <code>DataFrame.pivot</code>:</a></li> </ul> <block...
python|pandas|dataframe|pivot
2
9,445
70,599,088
Row sums of dataframe with variable column indexes (Python)
<p>I have a dataframe that has a few million rows. I need to calculate the sum of each row from a particular column index up until the last column. The column index for each row is unique. An example of this, with the desired output, will be:</p> <pre><code>import pandas as pd df = pd.DataFrame({'col1': [1, 2, 2, 5, N...
<p>You can create a like-Indexed DataFrame that lists all of the column positions and then by comparing this DataFrame with <code>df_ind</code> you can create a mask for the entire original DataFrame.</p> <p>Then <code>mask</code> the original DataFrame and <code>sum</code> to get the row sums based on the appropriate ...
python|pandas|sum|row
2
9,446
70,669,850
pandas merge ignore duplicate merged rows
<p>I am trying to merge below two data frames but I am not getting the expected result.</p> <pre><code>import pandas as pd previous_dict = [{&quot;category1&quot;:&quot;Home&quot;, &quot;category2&quot;:&quot;Power&quot;,&quot;usage&quot;:&quot;15&quot;,&quot;amount&quot;:&quot;65&quot;}, {&quot;catego...
<p>I think this is occurring due to the duplication in the columns you are joining on. One way to fix this is to also use the index as follows:</p> <pre><code>df_merge = pd.merge(df_previous.reset_index(), df_current.reset_index(), on=['category1','category2', 'index'], how='outer',indicator=True, suffixes=('', '_y')) ...
python|pandas|merge
2
9,447
70,562,007
How to use interpn to interpolate in a dataframe?
<p>I am trying to interpolate a dataframe but am having no luck. I have a dataframe with a distance header and a wind component header that I am working with.</p> <p>The wind components are split with a <code>20</code> unit difference and the distance by <code>10</code>. I would like to be able to interpolate to within...
<p>There's no need to transform your data, you already have a 2D array and can use it as-is. You got the axes wrong: the first axis (axis 0) is the rows of the dataframe, the second axis (axis 1) the columns.</p> <pre><code>arr = df.to_numpy() dist = df.index.to_numpy() wind = df.columns.to_numpy() x, y = np.meshgrid(...
python|pandas|dataframe|scipy|interpolation
1
9,448
70,714,317
TypeError: the first argument must be callable when calling tensorflow optimizer `apply_gradients`
<p>I hope someone can help me resolve this issue which has been driving me crazy for days. I am building something somehow inspired to <a href="https://keras.io/examples/rl/actor_critic_cartpole/" rel="nofollow noreferrer">this</a> keras example. I am trying to manually calculate the gradient of a network but I can't f...
<p>I also had the same error and found the solution. In my case, the initialization of the optimizer:</p> <pre><code>optimizer = keras.optimizers.Adam(learning_rate=learning_rate) </code></pre> <p>was using the variable <code>learning_rate</code> which was <code>None</code>. initializting with a number or simply:</p> <...
python|tensorflow|keras|deep-learning|reinforcement-learning
0
9,449
27,322,876
Trouble plotting pandas DataFrame
<p>I have a pandas DataFrame that has 2 columns one of the columns is a list of dates in this format: '4-Dec-14' the other column is a list of numbers. I want to plot a graph with the dates on the x-axis and numbers that correspond with that date on the y-axis. Either a scatter plot or line graph. I was trying to follo...
<p>You should first convert the strings in the date column, to actual datetime values:</p> <pre><code>df['date'] = pd.to_datetime(df['date']) </code></pre> <p>Then you can plot it, either by setting the date as the index:</p> <pre><code>df = df.set_index('date') df['y'].plot() </code></pre> <p>or by specifying x an...
python|python-2.7|numpy|matplotlib|pandas
4
9,450
27,238,924
Converting List of Numpy Arrays to Numpy Matrix
<p>I have a list of lists, <code>lists</code> which I would like to convert to a numpy matrix (which I would usually do by <code>matrixA = np.matrix(lists)</code>. The len of each list in <code>lists</code> is 7000, and the <code>len(lists)</code> is 10000.</p> <p>So when I perform <code>matrixA = np.matrix(lists)</c...
<p>I tried to recreate, but I can't:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; arrs = np.random.randn(10000, 7000) &gt;&gt;&gt; arrs array([[ 1.07575627, 0.16139542, 1.92732122, ..., -0.26905029, 0.73061849, -0.61021016], [-0.61298112, 0.58251565, -1.0204561 , ..., 1.73095028, ...
python|arrays|numpy|matrix
1
9,451
14,364,203
How do you install numpy when you're not a superuser?
<p>I've downloaded the python binary file and then opened it in my home folder using</p> <pre><code>tar xzvf Python-2.7.3.tgz </code></pre> <p>This seems to work and when I run </p> <pre><code>~/Python-2.7.3/python </code></pre> <p>it works great. However when I try to import numpy, apparently it is not included....
<p>Use <a href="https://github.com/utahta/pythonbrew" rel="nofollow">pythonbrew</a> to install Python into your $HOME folder:</p> <pre><code>$ pythonbrew install 2.7.2 </code></pre> <p>Then switch your current shell to use your local Python install:</p> <pre><code>$ pythonbrew use 2.7.2 </code></pre> <p>Now you sho...
python|numpy|installation
1
9,452
14,885,660
Numpy loadtxt rounding off numbers
<p>I'm using numpy loadtxt function to read in a large set of data. The data appears to be rounded off. for example: The number in the text file is -3.79000000000005E+01 but numpy reads the number in as -37.9. I've set the dypte to np.float64 in the loadtxt call. Is there anyway to keep the precision of the original da...
<p><code>loadtxt</code> is not rounding the number. What you are seeing is the way NumPy chooses to <em>print</em> the array:</p> <pre><code>In [80]: import numpy as np In [81]: x = np.loadtxt('test.dat', dtype = np.float64) In [82]: print(x) -37.9 </code></pre> <p>The actual value is the np.float64 closest to the ...
python|numpy
7
9,453
14,395,678
How to drop extra copy of duplicate index of Pandas Series?
<p>I have a Series <code>s</code> with duplicate index :</p> <pre><code>&gt;&gt;&gt; s STK_ID RPT_Date 600809 20061231 demo_str 20070331 demo_str 20070630 demo_str 20070930 demo_str 20071231 demo_str 20060331 demo_str 20060630 demo_str 2006...
<p>You can groupby the index and apply a function that returns one value per index group. Here, I take the first value:</p> <pre><code>In [1]: s = Series(range(10), index=[1,2,2,2,5,6,7,7,7,8]) In [2]: s Out[2]: 1 0 2 1 2 2 2 3 5 4 6 5 7 6 7 7 7 8 8 9 In [3]: s.groupby(s.index).first()...
python|pandas
25
9,454
25,359,658
Get row-index of the last non-NaN value in each column of a pandas data frame
<p>How can I return the row index location of the last non-nan value for each column of the pandas data frame and return the locations as a pandas dataframe?</p>
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.notnull.html#pandas.notnull" rel="noreferrer"><code>notnull</code></a> and specifically <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.idxmax.html#pandas.DataFrame.idxmax" rel="noreferrer"><code>idxmax</code></...
python-2.7|pandas|numpy|scipy|nan
8
9,455
25,064,506
What scipy statistical test do I use to compare sample means?
<p>Assuming <em>sample sizes are not equal</em>, what test do I use to compare sample means under the following circumstances (please correct if any of the following are incorrect):</p> <p><strong>Normal Distribution = True</strong> and <strong>Homogeneity of Variance = True</strong></p> <pre><code>scipy.stats.ttest_...
<h2>Fast answer:</h2> <p><strong>Normal Distribution = True</strong> and <strong>Homogeneity of Variance = False</strong> and <strong>sample sizes > 30-50</strong></p> <pre><code>scipy.stats.ttest_ind(sample1, sample2, equal_var=False) </code></pre> <h2>Good answer:</h2> <p>If you check the Central limit theorem, i...
python|numpy|statistics|scipy
10
9,456
25,128,537
Creating data histograms/visualizations using ipython and filtering out some values
<p>I posted a question earlier ( <a href="https://stackoverflow.com/questions/25107975/pandas-ipython-how-to-create-new-data-frames-with-drill-down-capabilities">Pandas-ipython, how to create new data frames with drill down capabilities</a> ) and it was pointed out that it is possibly too broad so I have some more spec...
<p>I think you need to convert duration (timedelta64) to int (assuming you have a duration). Then the .hist method will work.</p> <pre><code>from pandas import Series from numpy.random import rand from numpy import timedelta64 In [21]: a = (rand(3) *10).astype(int) a Out[21]: array([3, 3, 8]) In [22]: b = [timedelt...
python|pandas|histogram
0
9,457
29,012,212
Implementing common random numbers in a simulation
<p>I am building a small simulation in Python and I would like to use <a href="http://en.wikipedia.org/wiki/Variance_reduction">Common Random Numbers</a> to reduce variation. I know that I must achieve synchronization for CRN to work:</p> <blockquote> <p>CRN requires synchronization of the random number streams, wh...
<p>Yes. That is a valid approach to make it replicable, <strong>but only if</strong> you can <strong>guarantee</strong> that there is no randomness in the order in which the various instances of the various classes are instantiated. This is because if they are instantiated in a different order, then they will get a di...
python|python-2.7|numpy|random|simulation
2
9,458
29,294,983
How to calculate correlation between all columns and remove highly correlated ones using pandas?
<p>I have a huge data set and prior to machine learning modeling it is always suggested that first you should remove highly correlated descriptors(columns) how can i calculate the column wice correlation and remove the column with a threshold value say remove all the columns or descriptors having >0.8 correlation. al...
<p>The method here worked well for me, only a few lines of code: <a href="https://chrisalbon.com/machine_learning/feature_selection/drop_highly_correlated_features/" rel="noreferrer">https://chrisalbon.com/machine_learning/feature_selection/drop_highly_correlated_features/</a></p> <pre><code>import numpy as np # Crea...
python|pandas|correlation
59
9,459
29,155,745
Speed up function using cython
<p>I am trying to speed up one of my functions.</p> <pre><code>def get_scale_local_maximas(cube_coordinates, laplacian_cube): """ Check provided cube coordinate for scale space local maximas. Returns only the points that satisfy the criteria. A point is considered to be a local maxima if its value is greater than the...
<p>Your Python code could still be improved as you're not "already doing 98% in numpy": you're still iterating over the rows of the coordinate array and performing 1-2 checks per row.</p> <p>You could use numpy's "fancy indexing" and masks to get it <em>fully</em> in a vectorized form:</p> <pre><code>def get_scale_lo...
python|c|numpy|cython
4
9,460
33,651,243
plotting seismic wiggle traces using matplotlib
<p><a href="https://i.stack.imgur.com/XMhoQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XMhoQ.png" alt="enter image description here"></a></p> <p>I'm trying to recreate the above style of plotting using matplotlib.</p> <p>The raw data is stored in a 2D numpy array, where the fast axis is time.<...
<p>You can do this easily with <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.fill_betweenx" rel="noreferrer"><code>fill_betweenx</code></a>. From the docs:</p> <blockquote> <p>Make filled polygons between two horizontal curves.</p> <p>Call signature:</p> <p>fill_betweenx(y, x1, x2=0,...
python|numpy|matplotlib|plot
7
9,461
33,941,797
creating new column of values from parse function using pandas
<p>I have a csv containing a column 'start' with values of:</p> <pre><code>2015-09-28T12:58:42.831+03 2015-09-28T13:37:43.669+03 2015-09-28T14:11:31.383+03 2015-09-28T15:25:34.710+03 2015-09-28T18:06:02.106+03 </code></pre> <p>I want to create a new column in the dataframe with the parsed version of the time. So for ...
<p>You can create a new column in your data frame with the following command.</p> <pre><code>time_Test['parsed_datetime'] = [parse(i) for i in time_Test.start] </code></pre> <p>However, as suggested by EdChum, I would recommend using the <code>parse_dates=[the column index where your dates are]</code> flag when you r...
python|pandas
0
9,462
33,641,358
Can someone help me with TensorFlow?
<p>Google just opened up TensorFlow as opened source. I read it a bit but looks like you can only train it with their given MNIST data.</p> <p>I am looking for example code where i can train with my own data, and output results for my test file.</p> <p>where I have .csv file (like a sample per line) as training data ...
<p>The best solution I have found is:</p> <p><a href="https://github.com/google/skflow">https://github.com/google/skflow</a></p> <p>Charles</p>
tensorflow
5
9,463
23,796,191
Calculate rolling time difference in pandas efficiently
<p>I have a panel in pandas and am trying to calculate the amount of time that an individual spends in each stage. To give a better sense of this my dataset is as follows:</p> <pre><code>group date stage A 2014-01-01 one A 2014-01-03 one A 2014-01-04 one A 2014-01-05 t...
<p>Based your code (your <code>groupby/apply</code>), it looks like (despite your example ... but maybe I misunderstand what you want and then what Andy did would be the best idea) that you're working with a 'date' column that is a <code>datetime64</code> dtype and not an <code>integer</code> dtype in your actual data....
python|pandas
7
9,464
29,678,166
Pandas: Weighted median of grouped observations
<p>I have a dataframe that contains number of observations per group of income:</p> <pre><code>INCAGG 1 6.561681e+08 3 9.712955e+08 5 1.658043e+09 7 1.710781e+09 9 2.356979e+09 </code></pre> <p>I would like to compute the median income group. What do I mean? Let's start with a ...
<p>After glancing at a numpy example <a href="https://stackoverflow.com/questions/20601872/numpy-or-scipy-to-calculate-weighted-median">here</a>, I think <code>cumsum()</code> provides a good approach. Assuming your column of counts is called 'wt', here's a simple solution that will work most of the time (and see belo...
python|pandas|scipy
1
9,465
62,255,125
Trying to understand why none of my tensorflow-gpu import statements are working
<p>I'm using anaconda to run through a google code lab with tensorflow on my Windowsx64 machine. Followed directions and got the model trained nicely, all was good. Then I decided to try again with tensorflow-gpu. </p> <p>So I uninstalled tensorflow, and installed tensorflow-gpu using anaconda. (conda uninstall tensor...
<p>It's probably your tensorflow version is too old. I'm on 2.1 and that line works for me so I'm guessing they introduced config in 2.0 or something. Anyways, try the one that they deprecated instead. <a href="https://www.tensorflow.org/api_docs/python/tf/test/is_gpu_available" rel="nofollow noreferrer">https://www.te...
python|tensorflow|anaconda
0
9,466
62,062,231
Is it possible to involve a search bar on a DataFrame in Pandas?
<p>I have a DataFrame in Pandas which collects some data from an Excel document. I created a GUI with PyQt5 in order to make it look more interesting but here is the thing.</p> <p>Is it possbile to make a dynamic search bar in order to search through that DataFrame? For example, my DataFrame has over 3k+ rows and I wan...
<p>This can be done by subclassing <code>QAbstractTableModel</code> to create a custom table model that uses the underlying dataframe for supplying data to a <code>QTableView</code>. This custom model can then be combined with a <code>QProxyFilterSortModel</code> to filter the data in the table. To create a custom non-...
python-3.x|pandas|dataframe|user-interface|pyqt5
1
9,467
62,248,037
How to get the imagenet dataset on which pytorch models are trained on
<p><strong><em>Can anyone please tell me how to download the complete imagenet dataset on which the pytorch torchvision models are trained on and their Top-1 error is reported on?</em></strong></p> <p>I have downloaded Tiny-Imagenet from Imagenet website and used pretrained resnet-101 model which provides only 18% Top...
<p>Download the ImageNet dataset from <a href="http://www.image-net.org/" rel="nofollow noreferrer">http://www.image-net.org/</a> (you have to sign in)</p> <p>Then, you should move validation images to labeled subfolders, which could be done automatically using the following shell script: <a href="https://raw.githubu...
pytorch|torchvision|imagenet
1
9,468
62,217,844
Plotly doesn't draw barchart from pivot
<p>I am trying to draw a bar chart from the CSV data I transform using pivot_table. The bar chart should have the count on the y-axis and companystatus along the x-axis. </p> <p>I am getting this instead: <a href="https://i.stack.imgur.com/IVqpr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IVqpr...
<p>If you flatten the array with the <code>y</code> values, i.e. if you replace <code>y=df.values</code> with <code>y=df.values.flatten()</code>, your code will work as expected.</p> <pre><code>import plotly.graph_objects as go import plotly.offline as pyo import pandas as pd countcompany = pd.read_csv('https://raw.gi...
python|pandas|plotly
2
9,469
62,359,392
error when i try to sort values in descending order
<p>Im trying to sort the values in descending order but the code throws an error every time I run it. Im trying to run ANOVA and sort F Statistic values for every key value, and then sort the F statistic values in the descending oreder, everything until the sorting part seems to work fine.</p> <pre><code>def PAregress...
<p>You pass a whole series as value of the <code>by</code> argument. Instead you need to pass the column <strong>name</strong>, not the column itself:</p> <pre><code>Child = Child.sort_values(by=[Child.columns[2],Child.columns[1]], ascending=[False,True]) </code></pre> <p>Alternative: <code>by=Child.columns[2:0:-1].t...
python|pandas|numpy|regression
0
9,470
62,307,458
AttributeError - remove multiple whitespaces from multiple columns in dataframe
<p>I do this:</p> <pre><code>df[['InfoType', 'InfoLabel1', 'InfoLabel2']] = df[['InfoType', 'InfoLabel1', 'InfoLabel2']].apply(lambda x: ' '.join(x.split())) </code></pre> <p>and I receive this error:</p> <p>AttributeError: ("'Series' object has no attribute 'split'", 'occurred at index InfoType')</p> <p>the column...
<p>The <code>x</code> in your apply won't be the value of the individual cells, but rather a series (I think of each row). Hence your error.</p> <p>Luckily for you, there is a much easier way to convert all white space into a single space, use regex and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/a...
pandas
3
9,471
51,509,939
Funnel restrictive analysis with groupby
<p>I am trying to create a funnel analysis with the following conditions. I want to know how many people which enter to the home a page make a search (number of people which make search / number of people which make a home search) and the number of people which make a buy from those which make a search but must be nece...
<p>I've used groupby and str.contains to match your events and count them. Hopefully this will help with the first part of your question.</p> <p>First I created a sample dataframe</p> <pre><code>df = pd.DataFrame({'id': [1, 1, 1, 2, 3, 3, 3, 3], 'event': ['home', 'home', 'search', 'home', 'home', 'search', 'sear...
python|python-3.x|pandas|numpy|pandas-groupby
0
9,472
51,132,201
Pandas IndexError: single positional indexer is out-of-bounds, with strange manner
<p>Hi I am trying to get a sql query output in a format to keep the file stats.</p> <p>I am checking if sql query has all the dates or not. If not adding a dataframe with date and zero values and then doing the concating them into one.</p> <p>df.iloc[0,1] prints the value 2018-07-02 but when checking in if statement...
<p>Your dataframe <code>df1t</code> has only one column. Therefore, slicing <code>df1t.iloc[0,1]</code> will fail with <code>IndexError</code>.</p> <p>Make sure your dataframe has the data you require for your logic, or change your logic to accommodate your data.</p> <p>The line <code>print dfc.iloc[0,1]</code>, whic...
python|python-2.7|pandas
1
9,473
51,376,941
Google cloud TPU: NotImplementedError: Non-resource Variables are not supported inside TPU computations
<p>I am trying to train my model using google cloud's TPUs. The model works fine on CPU and GPU, and I can run the TPU tutorials without any problems (so it is not a problem of connecting to TPUs). However, when I run my program on the TPU cloud I get an error. The most important line is probably the following:</p> <p...
<p>I have found a way to use the TPUs without using the <code>ctpu up</code> command, which solves the problem. I simply do everything exactly as I would do it to run my code on cloud GPUs: </p> <p>-- see documentation here: <a href="https://cloud.google.com/ml-engine/docs/tensorflow/getting-started-training-predictio...
tensorflow|google-cloud-platform|google-cloud-tpu
0
9,474
51,452,246
Repeat columns as rows in python?
<pre><code> Fruit January Shipments January Sales February Shipments February Sales ------------ ------------------- --------------- -------------------- ---------------- Apple 30 11 18 31 Banana 12 ...
<p>one way is to use modify the column to a multi level then use <code>stack</code>. Let suppose your dataframe is called df. First set the column Fruit as index, then define the multilevel columns:</p> <pre><code>df = df.set_index('Fruit') # manual way to create the multiindex columns #df.columns = pd.MultiIndex.from...
python|pandas|dataframe
2
9,475
51,158,467
Trying to implement experience replay in Tensorflow
<p>I am trying to implement experience replay in Tensorflow. The problem I am having is in storing outputs for the models trial and then updating the gradient simultaneously. A couple approaches I have tried are to store the resulting values from sess.run(model), however, these are not tensors and cannot be used for gr...
<p>When you call <code>tf.assign(a, tf.Variable(i))</code> this does not actually immediately assign the value of the second variable to the first one. It just create an operation in the NN to do the assignment when <code>sess.run(...)</code> is called. </p> <p>When it is called all 10 assignments try to do their assi...
tensorflow|assign|policy-gradient-descent
0
9,476
51,125,969
loading EMNIST-letters dataset
<p>I have been trying to find a way to load the EMNIST-letters dataset but without much success. I have found interesting stuff in the structure and can't wrap my head around what is happening. Here is what I mean:</p> <p>I downloaded the .mat format <a href="https://www.nist.gov/itl/iad/image-group/emnist-dataset" re...
<p>Because of the way the dataset is structured, the array of image arrays can be accessed with <code>mat['dataset'][0][0][0][0][0][0]</code> and the array of label arrays with <code>mat['dataset'][0][0][0][0][0][1]</code>. For instance, <code>print(mat['dataset'][0][0][0][0][0][0][0])</code> will print out the pixel v...
python|python-3.x|numpy|scipy|mnist
6
9,477
51,331,721
writing pandas dataframe with timedeltas to parquet
<p>I can't seem to write a pandas dataframe containing timedeltas to a parquet file through pyarrow.</p> <p>The pyarrow documentation specifies that it can handle numpy <code>timedeltas64</code> with <code>ms</code> precision. However, when I build a dataframe from numpy's <code>timedelta64[ms]</code> the datatype of ...
<p><a href="https://fastparquet.readthedocs.io/en/latest/" rel="noreferrer">fastparquet</a> supports the timedelta type.</p> <p>First <a href="https://fastparquet.readthedocs.io/en/latest/install.html" rel="noreferrer">install</a> fastparquet, eg.:</p> <pre><code>pip install fastparquet </code></pre> <p>Then you can...
python|pandas|parquet|pyarrow
11
9,478
48,418,468
Tensorflow keras frozen .pb model returns bad results on android
<p>I created my model using Keras with transfer learning on IncpetionV3, and exported it to a <em>.pb</em> file using the following python code:</p> <pre><code>MODEL_NAME = 'Model_all1' def export_model(saver, model, input_node_names, output_node_name): tf.train.write_graph(K.get_session().graph_def, 'out_all2', ...
<p>If you are sure about your image pre-processing steps. Then the problem might be the same as mine. I faced the same problem and I find an answer. It is <a href="https://stackoverflow.com/questions/49474467/export-keras-model-to-pb-file-and-optimize-for-inference-gives-random-guess-on/49582776#49582776">here</a> for ...
android|python|tensorflow|keras|protocol-buffers
0
9,479
48,204,584
Rename Pandas DataFrame inside function does not work
<p>I want to implement this function in order to create new columns with new names. If I apply line by line the code works perfectly. If I run the function, the line lag.columns = [rename] does not work. </p> <p>What is happening?</p> <pre><code>T = [50, 48, 47, 49, 51, 53, 54, 52] v1 = [1, 3, 2, 4, 5, 5, 6, 2] v2 ...
<p>this works for me:</p> <pre><code>import pandas as pd T = [50, 48, 47, 49, 51, 53, 54, 52] v1 = [1, 3, 2, 4, 5, 5, 6, 2] v2 = [2, 5, 4, 2, 3, 1, 6, 9] dataframe = pd.DataFrame({'T': T, 'v1': v1, 'v2': v2}) def timeseries_to_supervised(data, ts=1, dropnan=True): # n_vars = 1 if type(data) is list else data...
python|pandas|dataframe
1
9,480
48,163,352
Error running Object Detection training in google ML engine - grpc epoll fd: 3
<p>I'm trying to train Object Detection model with gcloud ml-engine,reference to the official documents <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/running_on_cloud.md" rel="nofollow noreferrer">https://github.com/tensorflow/models/blob/master/research/object_detection/g3do...
<p>Only runtime version 1.2 is supported currently. We are working on other versions.</p>
tensorflow|grpc|google-cloud-ml
1
9,481
48,170,398
How do I change taking the mean based on the length of the list? (Python)
<p>I have a list containing lists containing arrays, something like this:</p> <pre><code>A = [ [ array([[ 1., 4.3, 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]]) ], [ array([[ 5., 0., 0., 0.], [ 0...
<p>You could just use a list comprehension:</p> <pre><code>&gt;&gt;&gt; np.mean([A[i][0] for i in range(len(A))], axis=0) </code></pre> <p>Or shorter, more readable and "pythonic":</p> <pre><code>&gt;&gt;&gt; np.mean([a[0] for a in A], axis=0) array([[ 3. , 2.15, 0. , 0. ], [ 0. , 0. , 0. , 0. ],...
python|numpy
1
9,482
48,254,436
Python Pandas Dataframe - compute difference between rows and take the minimum one
<p>I have a Pandas <code>Dataframe</code> <code>D</code> storing a large database. I also have a smaller <code>DataFrame</code> <code>C</code> with 10 rows, containing exactly the same columns as the main one, including column '<code>price</code>'. For each row <code>r</code> in the main dataframe <code>D</code> I want...
<p>Use <code>np.searchsorted</code> to index into a sorted version of <code>C.price</code>.</p> <pre><code>p1 = D.price.values v = np.sort(C.price.values) p2 = v[np.searchsorted(v, p1) - 1] p2 array([ 0.34, 3.24, 0.34, 9.77, 3.24, 3.24, 6.34, 6.34, 0.34]) </code></pre> <p></p> <p>Now, subtract them <code>p...
python|pandas|dataframe
1
9,483
48,875,447
Pandas: Convert Rare Entries in Column to Common Value
<p>I have a Pandas DataFrame, <code>df</code>, with a column called <code>LocationNormalized</code>. I've examined how often each value occurs with <code>value_counts()</code> and there are values that occur very rarely.</p> <p>So I want to convert these rare values to "RARE". Specifically, if a value occurs in the ...
<p>Use <code>groupby</code> + <code>transform</code> instead of <code>value_counts</code>, it becomes easier to create a mask to set values accordingly.</p> <pre><code>m = df.groupby("LocationNormalized").transform('count').lt(10) df.loc[m, "LocationNormalized"] = "RARE" </code></pre> <hr> <p>Demo with a <code>Serie...
python|pandas
2
9,484
48,721,620
What is the purpose of thread in tensorflow queue operation?
<pre><code>images, labels = tf.train.batch([image, label], batch_size=32, num_threads=4) </code></pre> <p>I often see a queue created with <code>num_threads</code> and the threads are said to be for enqueue operation. I don't quite understand the purpose of setting multiple threads for enqueue, because the way I see i...
<p>From <a href="https://www.tensorflow.org/versions/r1.1/programmers_guide/threading_and_queues" rel="nofollow noreferrer">Threading and Queues tutorial</a>:</p> <blockquote> <p>For example, a typical input architecture is to use a <code>RandomShuffleQueue</code> to prepare inputs for training a model:</p> <...
python|multithreading|tensorflow|queue|python-multithreading
1
9,485
48,511,285
Python pandas conditional column creation with aggregates
<p>I am trying to create a column that returns True if the P/E is in the lower quartile of all P/E in my dataframe. Below is what i have done so far.</p> <p>First i defined a function:</p> <pre><code>def pe_cond(df): if df['P/E'] &lt;= df['P/E'].quantile(0.1): return 1 else: return 0 </code></...
<p>I can't do this in a repl quite yet but this may work for you</p> <pre><code>mask = df['P/E'] &lt;= df['P/E'].quantile(0.1) df.loc[mask, 'pe_cond'] = 1 df.loc[~mask, 'pe_cond'] = 0 </code></pre> <p>This is using <code>.loc</code> to find the subset of the <code>DataFrame</code> that fulfills the logic defined in t...
python|pandas|dataframe
0
9,486
70,875,761
Python : Split string every three words in dataframe
<p>I've been searching around for a while now, but I can't seem to find the answer to this small problem.</p> <p>I have this code that is supposed to split the string after every three words:</p> <pre><code>import pandas as pd import numpy as np df1 = { 'State':['Arizona AZ asdf hello abc','Georgia GG asdfg hello ...
<p>For efficiency, you can use a regex and <code>str.extractall</code> + <code>groupby</code>/<code>agg</code>:</p> <pre><code>(df1['State'] .str.extractall(r'((?:\w+\b\s*){1,3})')[0] .groupby(level=0).agg(list) ) </code></pre> <p>output:</p> <pre><code>0 [Arizona AZ asdf , hello abc] 1 [Georgia GG asdfg , hel...
python-3.x|pandas|tokenize
1
9,487
51,997,022
Fast way to apply custom function to every pixel in image
<p>I'm looking for a faster way to apply a custom function to an image which I use to remove a blue background. I have a function that calculates the distance each pixel is from approximately the blue colour in the background. The original code with a loop looked like this:</p> <pre><code>def dist_to_blue(pix): rd...
<p>This should be a lil bit faster ... ;)</p> <pre><code>import numpy as np blue = np.full_like(image, [76,150,250]) mask = np.sum((image-blue)**2,axis=-1) &lt; 12000 image[mask] = [255,0,255] </code></pre> <p>Here you're generating the ideal blue image, squaring the difference of the images pixel by pixel, then sum...
python|image|numpy
2
9,488
51,818,047
How to create an object of type numpy.int8 in a C numpy extension?
<p>I have created my own class in a C Python extension. I want it to behave like a numpy array.</p> <p>Let's say my class is a myarray. I can index it using the slice notation. This means that my implementation of the <code>mp_subscript</code> function of the <code>mapping_methods</code> looks correct. I can further i...
<p>Found out I have to call <code>PyArray_Scalar</code> for this.</p>
python|numpy|cpython|python-c-api
0
9,489
51,586,114
How can i extract day of week from timestamp in pandas
<p>I have a timestamp column in a dataframe as below, and I want to create another column called <code>day of week</code> from that. How can do it?</p> <p>Input:</p> <pre><code>Pickup date/time 07/05/2018 09:28:00 14/05/2018 17:00:00 15/05/2018 17:00:00 ...
<p>You can use weekday_name</p> <pre><code>df['date/time'] = pd.to_datetime(df['date/time'], format = '%d/%m/%Y %H:%M:%S') df['Day of Week'] = df['date/time'].dt.weekday_name </code></pre> <p>You get</p> <pre><code> date/time Day of Week 0 2018-05-07 09:28:00 Monday 1 2018-05-14 17:00:00 Monday 2 2018-05...
python|python-3.x|pandas
11
9,490
51,812,095
Is pandas a local-only library
<p>I recently started coding, but took a brief stint. I started a new job and I’m under some confidential restrictions. I need to make sure python and pandas are secure before I do this—I’ll also be talking with IT on Monday </p> <p>I was wondering if pandas in python was a local library, or does the data get sent to ...
<p>Creating a <code>DataFrame</code> out of a dict, doing vectorized operations on its rows, printing out slices of it, etc. are all completely local. I'm not sure why this matters. Is your IT department going to say, "Well, this looks fishy—but some random guy on the internet says it's safe, so forget our policies, we...
python|pandas
1
9,491
42,127,156
tensorflow TF-slim inceptionv3 training loss curve is strange
<p>TF-slim inceptionv3 train from scratch</p> <p>I use slim/train_image_classifier.py to train a inception_v3 model on my own dataset: python train_image_classifier.py --train_dir=${TRAIN_DIR} --dataset_name=mydataset --dataset_split_name=train --dataset_dir=${DATASET_DIR} --model_name=inception_v3 --num_clones=2</p> ...
<p>You are plotting the graph for total loss after n steps(which is probably number_of_steps if you are using tf.contrib.slim train method) in your training while the loss thats logged is for every 10 steps. Hope this helps! </p>
tensorflow|tf-slim
0
9,492
64,577,273
Pandas getting unique index after concatenating list of dataframes
<p><strong>Problem:</strong> I have the following pandas dataframe object which was initially concatenated based on a dataframes list (in which each dataframe <code>df_*</code> carries <code>check_*</code> information). Below dataframe is only an example, the real one carries more (stage, unit) combinations (and I don'...
<p>Try</p> <pre><code>df = df.groupby(['stage', 'unit'], as_index=False).first() </code></pre>
python|pandas
0
9,493
47,846,320
Python - How to save spectrogram output in a text file?
<p>My code calculates the spectrogram for <code>x</code>, <code>y</code> and <code>z</code>. </p> <p>I calculate the magnitude of the three axis first, then calculate the spectrogram.</p> <p>I need to take the spectrogram output and save it as one column in an array to use it as an input for a deep learning model.</p...
<p>Matplotlib function <a href="https://matplotlib.org/api/_as_gen/matplotlib.pyplot.specgram.html?highlight=matplotlib%20pyplot%20specgram#matplotlib.pyplot.specgram" rel="nofollow noreferrer">specgram</a> has 4 outputs : </p> <blockquote> <p><strong>spectrum</strong> : 2-D array</p> <p>Columns are the periodo...
python-3.x|numpy|signal-processing|spectrum|spectrogram
1
9,494
49,109,053
FailedPreconditionError: Attempting to use uninitialized value
<p>I am trying to put together a neural network, and I want to save the weights with which I initialise the network for later use. </p> <p>This is the code that creates the network:</p> <pre><code>def neural_network_model(data, layer_sizes): num_layers = len(layer_sizes) - 1 # hidden and output layers layers ...
<p>You need to create the <code>variable initializer</code> in the end, when you are done creating the graph.<br> When you call <code>tf.global_variable_initializer()</code>, it takes all the trainable variables that have been created up until that point. So, if you define this before creating your layers (and variable...
python-3.x|serialization|tensorflow
1
9,495
58,996,519
Populate Pandas Dataframe with normal distribution
<p>I would like to populate a dataframe with numbers that follow a normal distribution. Currently I'm populating it randomly, but the distribution is flat. Column a has mean and sd of 5 and 1 respectively, and column b has mean and sd of 15 and 1.</p> <pre><code>import pandas as pd import numpy as np n = 10 df = pd...
<p>Try this. <code>randint</code> does not select from normal dist. <code>normal</code> does. Also no idea where you came up with 100 and 110 in <code>min</code> and <code>max</code> args for <code>b</code>.</p> <pre><code>n = 10 a_bar = 5; a_sd = 1 b_bar = 15; b_sd = 1 df = pd.DataFrame(dict(a=np.random.normal(a_bar,...
python|pandas|numpy
4
9,496
58,966,588
why np.concatenate() can be used for class 'PIL.Image.Image'?
<p>I'm reading someone's transform.py, and there is a code which really confuses me. Here it is:</p> <pre><code>np.concatenate(img_group, axis=2) </code></pre> <p>however, the <code>img_group</code> here is a sequence of <code>&lt;class 'PIL.Image.Image'&gt;</code>, and I've looked through the docs of np.concatenate(...
<p>Numpy operates on <a href="https://docs.scipy.org/doc/numpy/reference/arrays.interface.html" rel="nofollow noreferrer">array-like</a> objects. Here's a <a href="https://stackoverflow.com/questions/40378427/numpy-formal-definition-of-array-like-objects">link</a> to a question regarding what constitutes array-likeness...
python|numpy|python-imaging-library
1
9,497
58,687,266
The best way to expand the dimension of a numpy array so as to meet different requirements
<p>I have a mask <code>m</code> of shape <code>[bz]</code> and a dictionary <code>d</code> contains many different ndarrays, e.g. <code>d['s'].shape=(bz, 84, 84, 4)</code>, <code>d['r'].shape=(bz, 1)</code> and etc. All have the same first dimension of size <code>bz</code>, but the rest may vary. I want to expand the d...
<p>You can simply do -</p> <pre><code>for k, v in d.items(): d[k] = (v.T*m).T </code></pre> <p>So, we are basically pushing the first axis to the end, so that <code>v</code> becomes broadcastable against <code>m</code>. Then, multiply with <code>m</code>. Finally, pushing the last axis back to the front.</p> <p>...
python|numpy
1
9,498
58,696,183
generate a column delta based on a constraint
<p>I have a dataframe : </p> <pre><code>date_1 Count 01/09/2019 21 01/09/2019 21 01/09/2019 21 01/09/2019 21 01/09/2019 21 01/09/2019 21 01/09/2019 21 01/09/2019 21 01/09/2019 21 01/09/2019 21 01/09/2019 21 01/09/2019 21 01/09/2019 21 01/09/2019 21 01/09/2019 21 01/09/2019 21 01/09/2019 21 01/09/2...
<p>Use <a href="https://pandas-docs.github.io/pandas-docs-travis/reference/api/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>Groupby.transform</code></a> to transform Column Count in a Serie with 2or 4 using <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" re...
python|pandas|numpy
1
9,499
70,199,004
Check if condition is True with .loc and if is set 1
<pre><code>varv = -1 df: Open VarC Position Date 2019-11-25 10:00:00 30.38 -0.325098 0.0 2019-11-25 16:00:00 30.59 -1.538955 0.0 2019-11-26 10:00:00 30.56 -2.244309 0.0 2019-11-26 16:00:00 ...
<p>Try this:</p> <pre><code>df['Position'] = df['Position'].where(df['VarC'] &gt; varv, 1) </code></pre> <p>Output:</p> <pre><code>print(df) Open VarC Position Date 2019-11-25 10:00:00 30.38 -0.325098 0.0 2019-11-25 16:00:00 30.59 -1.538955 ...
python|pandas
0