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
357,500
49,451,229
Error using the pre-trained resent model for object detection in tensorflow
<p>I created a saved model from the pre-trained resnet50 model for serving using the tensorflow serving module. But when I try to run the model server i get this error: </p> <blockquote> <p>2018-03-23 13:36:37.130839: E external/org_tensorflow/tensorflow/core/common_runtime/executor.cc:651] Executor failed to creat...
<p>Well, it tells you whats wrong though it may be hard to see under all the details:</p> <p><em>"Check whether your GraphDef-interpreting binary is up to date with your GraphDef-generating binary"</em></p> <p>You seem to be using a very recent version of TensorFlow which has added a "dilations" parameter to Conv2D. ...
tensorflow|tensorflow-serving
0
357,501
49,467,949
Training accuracy showing 0.0
<p>My code:</p> <pre><code>def accuracy(pred_labels,true_labels): true_labels = tf.cast(tf.reshape(true_labels,[-1,1]),tf.float32) correct_pred = tf.equal(pred_labels,true_labels) accuracy = tf.reduce_mean(tf.cast(correct_pred,tf.float32)) return accuracy </code></pre> <p>When I run:</p> <pre><code>f...
<p>The reason is (probably) that <code>pred_labels</code> are <strong>not</strong> the <code>logits</code>. Trying something along the lines</p> <pre><code>correct = tf.cast(tf.nn.in_top_k(logits, true_labels, 1), tf.float32, name='correct') accuracy = tf.reduce_mean(correct, name='accuracy') </code></pre> <p>might h...
tensorflow
2
357,502
49,505,186
Processing data with multiple labels for same features Pandas
<p>I'm completely new to Pandas, so hopefully this question isn't too newb. </p> <p>Let's say I have the following data:</p> <pre><code> feature1 feature2 feature3 label a 2 3 1 b 2 3 1 c 2 3 0 </code></pre> <p>In this case, I want to get a single ...
<p>I think yes, it is correct. You can also specify column <code>label</code>:</p> <pre><code>processed_data = (df.groupby(['feature2','feature3'])['label'] .agg(lambda x:x.value_counts().index[0]) .reset_index()) </code></pre> <p>Another solution:</p> <pre><code>processed_data ...
pandas|pandas-groupby
1
357,503
49,689,425
Add time interval values in new column Pandas
<p>I have a large pandas dataframe (40 million rows) with the following format :</p> <pre><code>ID DATETIME TIMESTAMP 81215545953683710540 2017-01-01 17:39:57 1483243205 74994612102903447699 2017-01-01 19:14:12 1483243261 48126186377367976994 2017-01-01 17:19:29 1483243263 2352233...
<p>I would suggest using pandas' cut method to achieve this, preventing the need to explicitly loop through your DataFrame.</p> <pre><code>tmin, tmax = df['TIMESTAMP'].min(), df['TIMESTAMP'].max() bins = [i for i in range(tmin, tmax+10, 10)] labels = [i for i in range(len(bins)-1)] df['VALUE'] = pd.cut(df['TIMESTAMP'...
python|pandas|dataframe
1
357,504
49,420,274
`np.concatenate` a numpy array with a sparse matrix
<p>A dataset contains numerical and categorial variables, and I split then into two parts:</p> <pre><code>cont_data = data[cont_variables].values disc_data = data[disc_variables].values </code></pre> <p>Then I use <code>sklearn.preprocessing.OneHotEncoder</code> to encode the categorical data, and then I tried to mer...
<p>Sparse matrices are not subclasses of numpy arrays; so <code>numpy</code> methods often don't work. Use sparse functions instead, such as <code>sparse.vstack</code> and <code>sparse.hstack</code>. But all inputs then have to be sparse.</p> <p>Or make the sparse matrix dense first, with <code>.toarray()</code>, and...
python|numpy|scikit-learn
12
357,505
49,435,891
Pandas Average If in Python : Combining groupby mean with conditional statement
<p>I've looked through the forums and can't seem to figure this out. I have the following data. I assume the answer lies in the "groupby" function but I can't seem to work it out. </p> <pre><code>Date Hour Value 3DAverage 1/1 1 57 53.33 1/1 2 43 42.33 1/1 3 44 ...
<p>You can try rolling mean</p> <pre><code>df['3D Average'] = df.iloc[::-1].groupby('Hour').Value.rolling(window = 3).mean()\ .shift().sort_index(level = 1).values </code></pre>
python|pandas|conditional|trailing
2
357,506
49,358,558
TypeError: ("Cannot compare type 'Timestamp' with type 'str'", 'occurred at index 262224')
<p>I am trying to create a flag for date from datetime column. but getting an error after applying the below function. </p> <pre><code>def f(r): if r['balance_dt'] &lt;= '2016-11-30': return 0 else: return 1 df_obctohdfc['balance_dt_flag'] = df_obctohdfc.apply(f,axis=1) </code></pre>
<p>In pandas is best avoid loops, how working <code>apply</code> under the hood. </p> <p>I think need convert string to datetime and then cast mask to <code>integer</code> - <code>True</code> to <code>1</code> and <code>False</code> to <code>0</code> and change <code>&lt;=</code> to <code>&gt;</code>:</p> <pre><code>...
python-3.x|pandas
1
357,507
49,410,425
JSON from API call to pandas dataframe
<p>I'm trying to get an API call and save it as a dataframe. problem is that I need the data from the 'result' column. Didn't succeed to do that.</p> <p>I'm basically just trying to save the API call as a csv file in order to work with it.</p> <p>P.S when I do this with a "JSON to CSV converter" from the web it does...
<p>Looks like you need.</p> <pre><code>df = pd.DataFrame(j["result"]) </code></pre>
python|json|pandas
1
357,508
49,707,231
python pandas dataframe write multi row header
<p>data1</p> <pre><code>A B C D E &lt;--- columns a b c d e a b c d e a b c d e result what i want A B C D E &lt;--- columns A B C D E &lt;--- columns A B C D E &lt;--- columns a b c d e a b c d e a b c d e </code></pre> <p>I searched for this one and it finally failed :)<...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.from_arrays.html" rel="noreferrer"><code>MultiIndex.from_arrays</code></a>:</p> <pre><code>df.columns = pd.MultiIndex.from_arrays([df.columns] * 3) print (df) A B C D E A B C D E A B C D E 0 a b c d e 1 a...
pandas|dataframe|pandas.excelwriter
7
357,509
49,774,179
Python: get boundingbox coordinates for each cluster in segmentation map (2D numpy array)
<p>Python:</p> <p>I got a segmentation map (2D numpy array) with class values (integer 0 to N) for each pixel of the original img and i want to find the bounding box coordinates for each connected cluster in the segmentation map. </p> <p>EDIT: there might be more than one cluster per class in the map!</p> <p>I guess...
<h1>Complete answer</h1> <p>There's an existing function <a href="https://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.ndimage.measurements.find_objects.html#scipy-ndimage-measurements-find-objects" rel="nofollow noreferrer"><code>scipy.ndimage.measurements.find_objects</code></a> that allllmost does exac...
python|arrays|numpy|label|bounding-box
3
357,510
49,469,300
Pandas Dataframe - find the row with minimum value based on two columns but greater than 0
<p>I have a dataframe with 3 columns: x, y, time. There are a few thousand rows.</p> <p>What I want to do is retrieve the row with the minimum time but I would like that the minimum should not be 0. </p> <p>e.g. </p> <pre><code>x y time 240 1 28.5 240 2 19.3 240 240 0 240 19 9.7 </code></...
<p>Try this:</p> <pre><code>In [69]: df.loc[df.time&gt;0, 'time'].idxmin() Out[69]: 3 </code></pre> <p>or</p> <pre><code>In [72]: df.loc[[df.loc[df.time&gt;0, 'time'].idxmin()]] Out[72]: x y time 3 240 19 9.7 </code></pre>
python|pandas
5
357,511
49,683,770
Separating different points with different colors on a scatter plot
<p>This is a code I've written:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt data1 = pd.read_csv('F:\HCSE\sample_data1.csv',sep=';') colnames = data1.columns plt.plot(data1.iloc[:,0],data1.iloc[:,2],'bs') plt.ylabel(colnames[2]) plt.xlabel(colnames[0]) plt.show() </code></pre> <p>This is the d...
<p>I think you're looking for something like this:</p> <pre><code>cols = {0: 'red', 1: 'blue'} plt.scatter(data1.Age, data1.LOS, c=data1.Gender.map(cols)) </code></pre>
python|pandas|matplotlib
1
357,512
49,637,161
Grouping certain pandas results into single Excel tab
<p>I am writing a script that connects to a Teradata DB, reads in data from a single table, and runs some analysis on that table. </p> <p>The script I have below (made generic for this question) works fine for the most part but I have 2 questions...</p> <ol> <li>How can I combine some of the results onto a single ta...
<p>For the first one, you should create a new dataframe that contains both the min and max, copying the index (if required):</p> <pre><code>min_max_df = pd.DataFrame(index=df.index) min_max_df["min"] = df.min(numeric_only=True) min_max_df["max"] = df.max(numeric_only=True) </code></pre> <p>You can also write several ...
python|excel|pandas
3
357,513
49,565,152
Curve fit an exponential decay function in Python using given data points
<p>With the <code>curve_fit</code> function in SciPy I'm able to determine the coefficients that represent the curve shown in the plot below.</p> <pre><code>def func2(t, tau): return np.exp(-t / tau) t2 = np.linspace(0, 4, 50) y2 = func2(t2, 1.2) y2_noise = 0.2 * np.random.normal(size=t2.size) y2_curve_noise = y...
<p>To balance the fact that you're taking the exponent of a very large number, I've added a <code>t0</code> term to your equation:</p> <pre><code>def func4(t, a, t0, tau, c): return a * np.exp(-(t-t0)/ tau) + c # Initial guess p0 = np.array([4.0, 15400., 6.e2, 0.], dtype=np.float64) y4_initial = func4(t4, *p0) #...
python|numpy|scipy|curve-fitting
2
357,514
49,393,943
Insert a value in a numpy array column and keep the same size / row values
<p>The title is not the best but essentially I need to insert a value at (y,x) and shift the column until -1 is met where I insert a new value and delete -1. Here is an example to insert (100) at (2,1):</p> <pre><code>b = np.array([[1,-1,3], [2,5,6], [6,8,9], [10,4,3]) </code></pre> <p>would become:</p...
<p>First, let's import numpy and define your array:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; b = np.array([[1,-1,3], [2,5,6], [6,8,9], [10,4,3]]) </code></pre> <p>Now, to do your substitution, try:</p> <pre><code>&gt;&gt;&gt; b[:, 1] = np.concatenate((b[1:3, 1], [100], b[3:, 1])) &gt;&gt;&gt; b ar...
python|numpy
0
357,515
49,467,509
A faster way to remove close pixels
<p>I have an image with a thick line pixels, and line under it. I wanted to </p> <ol> <li>remove the bottom line</li> <li>thin the thick line</li> </ol> <p>so I used this loop:</p> <pre><code>N = 1000 im = (np.random.random((N, N)) - 0.5) xx,yy = np.where(im &gt; 0) for x,y in zip(xx,yy): for i in range(xmin,x...
<p>This is a case where Numba really shines. Without any real work, I immediately get a speedup of ~115x (times, not percent!). I don't have your entire code, but consider this example:</p> <pre><code>import numpy as np import numba from time import time @numba.jit def fun(): # Added just to make the code run ...
python|numpy
1
357,516
49,583,256
skip lines in a text file
<p>I'm very new to Python and we are using pandas to read a text file and retrieve data from specific lines.</p> <p>There are 44 lines listed in my text file but I only need from line 35 -44. And I need to exclude everything but "President", "Took office", "Left Office", "Party". I have this function but its not rea...
<p>You can omit the first N rows via the <code>skiprows</code> argument of the constructor:</p> <pre><code>df1 = pd.read_table( "presidents.txt", delimiter=',', usecols=["President ", "Took office ","Left office ", "Party "], skiprows=34 ) </code></pre> <p>You can also read the entire dataframe, then ...
python|python-3.x|pandas
0
357,517
49,579,103
Implementing with block manually produces different things
<p>Suppose I write</p> <pre><code>with some_method() ... </code></pre> <p>My impression is that the <code>with</code> command starts by calling the <code>__enter__()</code> method on whatever is returned by <code>some_method()</code>. (I believe the thing returned by <code>some_method()</code> is called a "contex...
<p>This is probably because you're discarding the context manager. Very few context managers are designed to be discarded after <code>__enter__</code>, without calling <code>__exit__</code>, and they may behave unpredictably if you do that. Some of them automatically call the equivalent of <code>__exit__</code> when ga...
python|tensorflow|contextmanager
2
357,518
49,468,431
Categorical crossentropy and label encoding
<p>I'm trying to code multiclass output and classes are ['A','B','C','D','E','F','G'].</p> <p>Could someone elaborate more next error message:</p> <p>"ValueError: You are passing a target array of shape (79, 1) while using as loss <code>categorical_crossentropy</code>. <code>categorical_crossentropy</code> expects ta...
<p>The problem lies in this portion of your code,</p> <pre><code># Encoding categorical data from sklearn.preprocessing import LabelEncoder, OneHotEncoder labelencoder_Y_1 = LabelEncoder() yy = labelencoder_Y_1.fit_transform(yy) </code></pre> <p>You forgot to one-hot encode the <code>yy</code>, please take note that ...
tensorflow|scikit-learn|keras
4
357,519
49,694,394
A better way to create a timeline of repeated event at a given frequency
<p>I have a square (pulse) signal which has a frequency <code>fq</code>, and is played between <code>t0</code> and <code>tf</code>. To create the timeline, I simply do:</p> <pre><code>import numpy as np t0 = 0 tf = 200 fq = 20 timeline = np.round(np.arange(t0, tf, 1/fq*1000), 3) </code></pre> <p>A frequency of 20 Hz...
<p>A simple way:</p> <pre><code>import numpy as np def burst_pulse(t0, tf, fq, n_pulse, fq_burst): timeline = np.arange(t0, tf, 1 / fq * 1000) burst = np.arange(n_pulse) / fq_burst * 1000 timeline_burst = (timeline[:, np.newaxis] + burst[np.newaxis, :]).reshape((-1,)) return np.round(timeline_burst, 3...
python|numpy|sequence
2
357,520
49,439,182
Python pandas: calculate revenue from price and quantity
<p>I have a dataframe that looks like the following:</p> <pre><code>df Out[327]: date store property_name property_value 0 2013-06-20 1 price 101 1 2013-06-20 2 price 201 2 2013-06-21 1 price 301 3 2013-06-21 2 price ...
<p>This is one way.</p> <pre><code>price = df[df['property_name'] == 'price'].set_index(['date', 'store'])['property_value'] quantity = df[df['property_name'] == 'quantity'].set_index(['date', 'store'])['property_value'] rev = (price * quantity).reset_index().assign(property_name='revenue') df = pd.concat([df, rev],...
python|pandas|vectorization|pandas-groupby
1
357,521
49,578,846
vectorize index lookup in pandas
<p>I'm looping thru a dataset trying to find values in an index. If the value isn't in the (multi-level) index, then I take a default value:</p> <pre><code>for i,row in df.iterrows(): if i in avg_days.index: df.at[i,'avg_days_to_n'] = round(avg_days.xs(i,axis=0)[1],0) else: df.at[i,'avg_days_t...
<p>The first part, matching all 3 indexes at the same time can be easily achieved with the <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html#pandas.merge" rel="nofollow noreferrer">merge</a> function, which is implemented in pandas. In order to maintain all the indexes found in <code>df<...
pandas|numpy|vectorization
2
357,522
49,434,432
*Vectorized* way to find indices of minimums for each column (excluding all already found indices)
<p>I have the following square DataFrame:</p> <pre><code>In [104]: d Out[104]: a b c d e a inf 5.909091 8.636364 7.272727 4.454545 b 7.222222 inf 8.666667 7.666667 1.777778 c 15.833333 13.000000 inf 9.166667 14.666667 d 4.444444...
<p>A loop is the only solution I can see here.</p> <p>But you can use <code>numpy</code> + <code>numba</code> to optimise.</p> <pre><code>from numba import jit @jit(nopython=True) def get_min_lookback(A, res): for i in range(A.shape[1]): res[i] = np.argmin(A[:, i]) A[res[i], :] = np.inf retur...
python|pandas|numpy
2
357,523
49,570,364
Return elements from 2D numpy array that satisfy certain conditions
<p>I have a (huge) 2D array. For example:</p> <pre><code>a=[[1,2],[2,3],[4,5]] </code></pre> <p>I need to extract from it the elements that satisfy certain conditions</p> <pre><code>a[:,0]&gt;1 and a[:,1]&gt;2 </code></pre> <p>such that I get in return an array with only elements that satisfy both the conditions</p...
<p>You need to make use of the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.logical_and.html" rel="nofollow noreferrer">(logical) and</a> in numpy:</p> <pre><code>result = a[np.logical_and(a[:,0] &gt; 1, a[:,1] &gt; 2)] </code></pre> <p>Does this work for you?</p> <p><strong>edit:</strong> In...
python|numpy
1
357,524
49,645,135
Pandas display extra unnamed columns for an excel file
<p>I'm working on a project using pandas library, in which I need to read an Excel file which has following columns:</p> <pre><code>'invoiceid', 'locationid', 'timestamp', 'customerid', 'discount', 'tax', 'total', 'subtotal', 'productid', 'quantity', 'productprice', 'productdiscount', 'invoice_products_id', 'prod...
<p>As discussed in comments the problem seems to be that, there is extra data after <code>last named</code> columns. That's why you are getting <code>Unnamed</code> columns. </p> <p>If you wanna drop these columns this is how you can ignore these columns</p> <pre><code>df_full = df_full[df_full.filter(regex='^(?!Unna...
python|pandas
6
357,525
27,967,596
Python pandas grouping for correlation analysis
<p>Assume two dataframes, each with a datetime index, and each with one column of unnamed data. The dataframes are of different lengths and the datetime indexes may or may not overlap.</p> <p>df1 is length 20. df2 is length 400. The data column consists of random floats.</p> <p>I want to iterate through df2 taking...
<p>Without knowing more specifics of the questions such as, why are you doing this or do dates matter, this will do what you asked. I'm happy to update based on your feedback.</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt import random df1 = pd.DataFrame({'a':[random.randint(0,...
python|pandas|correlation
0
357,526
28,213,520
Pandas dataframe.dot division method
<p>I am trying to divide two series of different length to return the matrix product dataframe of them.</p> <p>I can multiply them using the dot method (<a href="https://stackoverflow.com/a/19571460/1842478">from this answer</a>):</p> <pre><code># Create series average_read_intervals = pd.Series([10,20,30,40], ...
<p>To do an element wise division operation you can divide the values of each data frame like so:</p> <pre><code>matrix_div = pd.DataFrame(R.values/A.T.values, index=R.index, columns=A.index) </code></pre> <p>which produces the desired matrix of</p> <pre><code> a b c d z 10 5 3.333333 2.5 ...
python|matrix|pandas
4
357,527
28,378,959
import multiple txt files into numpy array with column0=datetime objects and column1=float values
<p>I have many text files that look like:</p> <pre><code>#comment 2012-01-01 00:00:00, 6542736.60466 2012-01-01 00:00:05, 6542736.60466 2012-01-01 00:00:10, 6568774.53588 2012-01-01 00:00:15, 6594812.46709 ... 2012-01-01 23:59:55, 6494801.44322 </code></pre> <p>There is a text file for each day so ultimately I would ...
<p>I think you're going to have a much better experience <a href="http://pandas.pydata.org/pandas-docs/stable/io.html#csv-text-files" rel="nofollow">reading csvs with pandas</a>:</p> <pre><code>In [11]: import pandas as pd In [12]: pd.read_csv('foo.csv', header=None, comment='#') Out[12]: 0 ...
python|python-2.7|numpy
1
357,528
28,148,101
Correlate a large image with a kernel in python using numpy/scipy
<p>I have an image (10000x10000 pixels) and I have a kernel (5x5 pixels). I want to find the place(s) in the image that best matches the kernel.</p> <p>I vaguely remember from my studies that I need to compute a correlation coefficient for each pixel in the large image with respect to the kernel. But having something ...
<p>This is usually referred to as <strong>template matching</strong> in image processing and most image processing packages will have something for it. If you can use scikit-image then you probably want <a href="https://scikit-image.org/docs/dev/auto_examples/features_detection/plot_template.html" rel="nofollow norefe...
python|numpy|scipy|correlation
1
357,529
28,129,287
How to properly upgrade numpy on Windows 7?
<p>It seems the whole world is using Linux or Mac, and I couldn't find any answer on the web to question "How to properly upgrade numpy on <strong>Windows 7</strong>?". I use Windows 7, python 2.7 and numpy 1.7.1, how do I upgrade to numpy 1.9.1 on my machine?</p>
<p>It will be based on your installation. </p> <ul> <li>First: try <code>pip install --upgrade numpy</code> </li> <li>also try here: <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow noreferrer">http://www.lfd.uci.edu/~gohlke/pythonlibs/</a></li> <li>also see: <a href="https://stackoverflow.com/ques...
python|numpy|windows-7
2
357,530
27,984,642
Creating index array in numpy - eliminating double for loop
<p>I have some physical simulation code, written in python and using numpy/scipy. Profiling the code shows that 38% of the CPU time is spent in a single doubly nested for loop - this seems excessive, so I've been trying to cut it down.</p> <p>The goal of the loop is to create an array of indices, showing which element...
<p>In pure Python you can do this using a dictionary in <code>O(N)</code> time, the only time penalty is going to be the Python loop involved:</p> <pre><code>&gt;&gt;&gt; arr1 = np.array([7.2, 2.5, 3.9]) &gt;&gt;&gt; arr2 = np.array([[7.2, 2.5], [3.9, 7.2]]) &gt;&gt;&gt; indices = dict(np.hstack((arr1[:, None], np.ara...
python|arrays|performance|numpy|indexing
2
357,531
28,058,419
Merging DataFrame row values into string by level
<p>If I have the following DataFrame...</p> <pre><code> code player_id 223336 4 223336 5 223336 4 225987 2 225987 3 225987 4 </code></pre> <p>How can I merge the "code" column into a string so the result would look like...</p> <pre><code> code pla...
<p>You could </p> <ul> <li>convert the code column values to strings (using <code>astype</code>), </li> <li>then use <code>groupby</code> to group those values according to the index, and finally </li> <li>aggregate the groups using <code>''.join</code></li> </ul> <hr> <pre><code>import pandas as pd df = pd.read_tab...
python|pandas
5
357,532
28,269,123
Singular matrix - python
<p>The following code shows a problem of singularity of a matrix, since working in Pycharm I get</p> <pre><code>raise LinAlgError("Singular matrix") numpy.linalg.linalg.LinAlgError: Singular matrix </code></pre> <p>I guess the problem is K but I cannot understand exactly how:</p> <pre><code>from numpy import zeros ...
<p>Inverting matrices that are very "close" to being singular often causes computation problems. A quick hack is to add a very small value to the diagonal of your matrix before inversion.</p> <pre><code>def getE(g, k): m = 10^-6 KInv = linalg.inv(k + numpy.eye(k.shape[1])*m) Ktrans = linalg.transpose(k) ...
python|numpy|transpose|inverse|singular
7
357,533
28,271,082
Cumulative sum in Python Pandas
<p>This is my table as dataframe:</p> <pre><code>col1 col2 col3 col4 col5 col6 col7 1 1 1 1 137 500 11 1 1 1 1 120 500 11 1 1 2 1 101 500 11 1 1 3 1 55 500 11 1 2 2 1 133 340 12 1 2 2 1 125 340 12 1 2 1 1 63 340 ...
<p>I think your attempt to use <code>cumsum</code> may not have worked because you didn't group by <code>col7</code>- it's apparent from your example calculations that you only calculate the cumulative sum within each value of <code>col7</code>, so I think you want:</p> <pre><code>df['cumsums'] = df.groupby('col7')['c...
python|pandas
3
357,534
28,348,383
How to use pandas.to_clipboard with comma decimal separator
<p>How can I copy a DataFrame <code>to_clipboard</code> and paste it in excel with commas as decimal?</p> <p>In R this is simple.</p> <pre><code>write.table(obj, 'clipboard', dec = ',') </code></pre> <p>But I cannot figure out in pandas <code>to_clipboard</code>.</p> <p>I unsuccessfully tried changing:</p> <pre><code>i...
<p>Since Pandas 0.16 you can use</p> <pre><code>df.to_clipboard(decimal=',') </code></pre> <p><a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_clipboard.html" rel="noreferrer">to_clipboard()</a> passes extra kwargs to <a href="https://pandas.pydata.org/pandas-docs/stable/generated/p...
python|pandas|number-formatting
8
357,535
73,426,172
Lengthening Pandas Dataframe by setting column headers as a row values and having a value column
<p>I am a bit stuck with how to reshape my dataframe into a shape that offers me more flexibility.</p> <p>My current dataframe is as follows.</p> <pre><code>Orginal_df = pd.DataFrame([['Action', 1, 5, 3], ['Comedy', 2, 4, 6], ['Drama', 3, 2, 10], ['Crime', 1, 6...
<p>In my opinion <code>pandas.melt()</code> will do the job, while you set the <em>Genre</em> as <code>id_vars=['Genre']</code>:</p> <pre><code>df.melt(id_vars=['Genre'], var_name='Name', value_name='Count') </code></pre> <h4>Example</h4> <pre><code>df = pd.DataFrame([['Action', 1, 5, 3], ['Comedy',...
python|pandas|dataframe
1
357,536
73,246,908
Python - round off a value
<p>I tried the following in my Jupyter notebook. When I round off value to 3 decimal points, its showing 3 decimal values. But when I round off to 2 decimal points, its showing 1 decimal value only.</p> <p>round(64.10343, 4) output: 64.1034</p> <p>round(64.10343, 3) output: 64.103</p> <p>round(64.10343, 2) <strong>outp...
<p>It happens because when you round to two decimal points after rounding 64.10 is left since second decimal is zero, output is not displayed.</p>
python|pandas
0
357,537
73,309,509
How can I train a tensorflow model on another local computer and get its return value?
<p>So currently I have one computer running MacOS and another computer with a GPU running windows. What's the best way to send data (in this case, 2 images or links to images) from the Mac to the Windows computer, train a model with Tensorflow on the Windows computer, then send the output of the model (another image) b...
<p>Personally I like:</p> <ol> <li>Connecting to the machine with the GPU via ssh</li> <li>Open a <a href="https://github.com/tmux/tmux/wiki" rel="nofollow noreferrer">tmux</a> session or something similar so that all that is printed and will be printed inside the terminal is not lost when I disconnect from the ssh. To...
python|tensorflow|server
0
357,538
73,361,231
Create a Boolean column for unique rows in a grouped data frame
<p>I have a grouped data frame <code>df_grouped</code>, I would like to create a new boolean column <code>df_grouped[&quot;Unique&quot;]</code> where for each subset of grouping, this column is <code>True</code> if the values of <code>location</code> is unique within the grouping &amp; <code>False</code> if it's not un...
<p>Use <a href="http://%5Bandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.duplicated.html" rel="nofollow noreferrer"><code>DataFrame.duplicated</code></a> with <code>keep=False</code> and inverted mask by <code>~</code>:</p> <pre><code>df['Unique'] = ~df.duplicated(['ID','Day', 'Location'], keep=Fals...
python|pandas|dataframe
1
357,539
73,340,272
Applying function to groups in dataframe, excluding current row value
<p>Let's say I have the following data:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">day</th> <th style="text-align: center;">query</th> <th style="text-align: right;">num_searches</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">1</td> <td style="...
<p>Given:</p> <pre><code> day query num_searches 0 1 abc 2 1 1 def 3 2 2 abc 6 3 3 abc 5 4 4 def 1 5 4 abc 3 6 5 abc 7 7 6 abc 8 8 7 abc 10 9 8 abc ...
python|pandas|dataframe|statistics
1
357,540
73,311,384
Selecting groups in pandas dataframe based on percentage of total
<pre><code>col_a col_b a 10 a 20 c 10 c 5 d 20 e 30 </code></pre> <p>The total of <code>col_b</code> is 95. I want to select only those rows where sum of <code>col_b</code> values exceeds 80% of the total (95). In this case, the sum by each group is</p> <pre><code>a 30 c 15 d...
<p>a way to do this is:</p> <pre class="lang-py prettyprint-override"><code>( df .set_index('col_a')[ df .groupby('col_a') .sum() .sort_values(by='col_b', ascending=False) .cumsum() .lt(df.col_b.sum()*0.8) ...
python|pandas
1
357,541
73,365,949
How to split all names and initials in dataframe stored without whitespace?
<p>I have a dataframe with a column containing names and initials. Sometimes one cell carries more than one name and they are entered without whitespace separating them, for example -</p> <pre><code>A B MclearyT WhitebottomIannis Clancy </code></pre> <p>I want to turn this into</p> <pre><code>A B Mcleary, T Whitebottom...
<pre><code>import pandas as pd pd.Series(['A B MclearyT WhitebottomIannis Clancy']).str.replace('([a-z])([A-Z])', r'\1, \2', regex=True) </code></pre> <hr /> <pre><code>0 A B Mcleary, T Whitebottom, Iannis Clancy </code></pre>
python|pandas|data-wrangling
2
357,542
73,300,786
Pass arguments to function while using apply to pandas series
<p>I want to pass an argument (dropna=False) to value_counts, when using apply with pandas dataframe:</p> <pre class="lang-py prettyprint-override"><code>columns = ['a','c'] df = pd.DataFrame({'a':[1,2,2,np.nan], 'b':[2,3,4,3], 'c': [4,np.nan,6,4]}) print (df.apply(pd.Series.value_counts)) #this works print (df['a'].va...
<p>IIUC you need pass like argument <code>dropna=False</code>:</p> <pre><code>print (df.apply(pd.Series.value_counts, dropna=False)) a b c 1.0 1.0 NaN NaN 2.0 2.0 1.0 NaN 3.0 NaN 2.0 NaN 4.0 NaN 1.0 2.0 6.0 NaN NaN 1.0 NaN 1.0 NaN 1.0 </code></pre> <p>Or lambda function:</p> <pre><code>pr...
python|pandas|apply
2
357,543
73,304,706
Empty Index in Pivot Tabele Pandas
<p>i have I have a table that I load as a dataframe with the help of a pandas. Next, I would like to create a PivotTable table:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Name</th> <th>Lang</th> <th>skills</th> </tr> </thead> <tbody> <tr> <td>Michael</td> <td>http</td> <td>1</td> </tr>...
<p>Replace <code>nan</code> with string like 'Other', then do the operation:</p> <pre><code>import pandas as pd import io import numpy as np data_string = &quot;&quot;&quot;Name Lang skills Michael http 1 Cristiano css 2 John js 3 Piter http 4 Michael css 3 Cristiano js 2 John http 1 Piter ...
python|pandas
1
357,544
73,196,271
Stuck on producing a piechart
<pre><code>1 Neutral 2 Positive 3 Positive 4 Neutral 5 Negative ... Name: Analysis, Length: 63664, dtype: object </code></pre> <p>How can i produce a pie chart for this column above i have no isea what to do next i tried finding the percentage myself:</p> <pre><code>po...
<p>You can use <code>value_counts</code> and then <code>plot.pie</code>:</p> <pre><code>df = pd.DataFrame(data=[&quot;Positive&quot;, &quot;Negative&quot;, &quot;Negative&quot;]) df.value_counts().plot.pie() </code></pre> <p>Output:</p> <p><a href="https://i.stack.imgur.com/l39IP.png" rel="nofollow noreferrer"><img src...
python|pandas|dataframe|pie-chart
1
357,545
73,387,519
Drop DataFrame specific columns if absent in a list, keeping every other columns
<p>I have a dataframe <code>df</code> that looks like this:</p> <pre><code> FT1 FT2 ... FT32 Style Rank ... 0 0.02 0.01 0.01 Black 7 1 0.01 0.04 0.01 Death 2 2 0.01 0.01 0.01 Hardcore 6 3 0.04 0.01 ...
<p>You can extract the FT columns, compare to your modified list and use it to <code>drop</code>:</p> <pre><code>FT_index=[1,4,5,7] cols = df.filter(like='FT').columns df2 = df.drop(columns=cols[~cols.isin([f'FT{i}' for i in FT_index])]) </code></pre> <p>output:</p> <pre><code> FT1 Style Rank 0 0.02 Bla...
python|pandas|list|dataframe|filter
1
357,546
73,413,907
Adding sheets to an existing Excel File via Python
<p>i'm working with a gui in Python, which i created via tkinter. Now i want to save some data(that i stored in a two dimensional List) in an excel file. I'm trying to do that in one function.</p> <p>Here is the Code that i use</p> <pre><code> def Convert(self): list_data_conv = self.list_data df=p...
<p>The ExcelWriter's default mode is &quot;write&quot;, in order to append to it, set mode to append ('a').</p> <p>Just replace it with :</p> <pre><code>writer = pd.ExcelWriter(excel_file, engine='openpyxl', mode='a') </code></pre> <p>If the code line above didn't work, try:</p> <pre><code>writer = pd.ExcelWriter(r'e...
python|python-3.x|excel|pandas
1
357,547
73,410,576
Generating Combinatorics With Numpy
<p>I am trying to implement a quick tool to find the combinations of a set of numbers <code>(0...k)</code>, for <code>j</code> lots of this array, where the sum across the row is equal to <code>k-j</code>, and <code>k&gt;=j</code></p> <p>For instance, for k=3, and j=2, I have all the following combinations:</p> <pre><c...
<p>For one, you don't have to consider the range up to <code>k</code>, but only up to <code>k-j</code>. Further, you could use <code>itertools.combinations</code> (if you are only interested in the set and not the order), as follows:</p> <pre><code>combs = np.array(list(combinations(range(k-j+1), j))) combs = combs[np....
python|numpy|combinations
1
357,548
73,426,201
how can plot multi line plot with legends as other column name
<p><a href="https://i.stack.imgur.com/UtgLQ.jpg" rel="nofollow noreferrer">enter image description here</a><a href="https://i.stack.imgur.com/mmZj5.png" rel="nofollow noreferrer">first image is plot which i want but with legend as the sentiment column values</a></p> <p>[data]</p> <p>is there is any subsituet to plot li...
<p>i am not sure if this is what you searching for</p> <pre><code>import matplotlib.pyplot as plt import numpy as np x = np.linspace(0,2*np.pi,200) y = x**2 dydx = np.cos(x) cmap = plt.get_cmap(&quot;hsv&quot;,1000) colors = cmap(np.linspace(0,1,200)) #200 - a tuple for each data point plt.scatter(x,y,c=colors) </c...
python|pandas|data-analysis
1
357,549
73,472,248
Cumulative Sum based on a Trigger
<p>I am trying to track cumulative sums of the 'Value' column that should begin every time I get 1 in the 'Signal' column.</p> <p>So in the table below I need to obtain 3 cumulative sums starting at values 3, 6, and 9 of the index, and each sum ending at value 11 of the index:</p> <div class="s-table-container"> <table...
<p>You can <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferrer"><code>pivot</code></a>, <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.bfill.html" rel="nofollow noreferrer"><code>bfill</code></a>, then <a href="https://pandas.pydata.org/doc...
python|pandas|iteration|cumsum
1
357,550
73,307,820
reshape nested json data in a dataframe using python to get desired output
<p>Hi I am attempting to reshape this json data within a dataframe using pandas.</p> <pre><code> id categories 1 3ee877e0 [{&quot;entity_def_id&quot;:&quot;category&quot;,&quot;permalink&quot;:&quot;blockchain&quot;,&quot;uuid&quot;:&quot;1fea6201&quot;,&quot;value&quot;:&quot;Blockchain&quot;},{&quot;...
<p>You could take the list of dicts in <code>categories</code>, pass it to <code>DataFrame()</code> as-is, and then insert your id column using <code>insert</code></p> <pre class="lang-py prettyprint-override"><code>import pandas as pd current_df = pd.DataFrame({&quot;id&quot;: &quot;3ee877e0&quot;,&quot;categories&qu...
python|pandas|dataframe|dataiku
0
357,551
73,258,053
How to use image from PIL ImageGrab without saving it to a file?
<p>I'm trying to compare the structural similarity of two images with the skimage package but it only works if use two images saved on my pc and not when I use an image created by ImageGrab from PIL even it's basically the same image.</p> <pre><code>def structural_sim(img1, img2): sim, diff = structural_similarity(...
<p>Your question confuses me, but I think you want to get a Numpy array, like you would from <code>cv2.imread()</code> so that you can use it with <code>scikit-image</code>. But you currently have a <code>PIL Image</code> instead.</p> <p>So, to get a Numpy array from a <code>PIL Image</code>, you need:</p> <pre><code>i...
python|numpy|python-imaging-library
0
357,552
73,192,622
How to create a dictionary with value list from dataframe
<p>I have a dataframe, like so:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Projects</th> <th>Goals</th> <th>Steps</th> </tr> </thead> <tbody> <tr> <td>Project A</td> <td>Goal 1</td> <td>NaN</td> </tr> <tr> <td>Project A</td> <td>NaN</td> <td>Step 1</td> </tr> <tr> <td>Project A</td> <t...
<p>You can build your dictionary by grouping successively by 'Projects' and 'Goals' aggregating the steps with <code>list</code>:</p> <pre><code>df[&quot;Goals&quot;] = df['Goals'].ffill() df = df.dropna() dict_out = {} for proj, sub_df in df.groupby('Projects'): sub_df = sub_df.drop('Projects', axis=1).groupby([...
python|pandas|dataframe|dictionary
1
357,553
73,286,843
Generating text/csv file for image path and mask path for semantic segmentation
<p>I have a huge set of images(60k) and masks(60k) that need to be loaded into a PyTorch dataloader for semantic segmentation.</p> <pre><code>Directory Structure: - Segmentation -images -color_left_trajectory_3000_00001.jpg -color_left_trajectory_3000_00002.jpg ... -mask...
<p>I recommend that you make a custom subclass from the <em>dataset</em> class. In the init function, the paths to the images and masks are generated and then saved. This is an example:</p> <pre><code>import torch from torch.utils.data import Dataset, DataLoader import os from PIL import Image class CustomData(Dataset...
pytorch|image-segmentation|dataloader|pytorch-dataloader
2
357,554
73,408,966
How to get duration of a condition (in index length) in a pandas column vectorized
<p>I have a data set with timeseries data. When a condition is met for a parameter I want to measure for how long that was.<br /> I can for loop through all the positions where the condition changes but that seems to be inefficient.</p> <p><em><strong>What is the best way to do this vectorized?</strong></em></p> <p><st...
<p>Mark the first <code>'0'</code> in a <code>'0'</code> group and mark the first <code>'1'</code> in a <code>'1'</code> group. Use <code>.loc</code> to select only those rows. Then do a <code>diff</code> on those. Use <code>.loc</code> to keep only the <code>diff</code>s for the first <code>'0'</code> rows. Then as...
python|pandas|dataframe|numpy|indexing
3
357,555
73,236,107
Convert MatchIt summary object into a pandas dataframe with pyr2
<p>I am using R's <code>MatchIt</code> package but calling it from Python via the <code>pyr2</code> package.</p> <p>On the R-side MatchIt gives me a complex result object including raw data and some additional statistic information. One of is a matrix I want to transform into a data set which I can do in R code like th...
<p>Ah, it is always the same phenomena: While formulating the question the answers jump'n right into your face.</p> <p>My (maybe not the best) solution is:</p> <ul> <li>Use real R code and run it with <a href="https://rpy2.github.io/doc/v2.9.x/html/robjects_rinstance.html" rel="nofollow noreferrer"><code>rpy2.robjects....
python|r|pandas|rpy2|propensity-score-matching
0
357,556
73,382,285
Getting financial data into data frames for multiple tickers
<p>here is the code :</p> <pre><code>**tickers = ['AMZN','AAPL','MSFT','DIS','GOOG'] # Created individual dataframes for each category of data and tickers BS0=yfs.get_balance_sheet(tickers[0]) IS0=yfs.get_income_statement(tickers[0]) CF0=yfs.get_cash_flow(tickers[0]) BS0.columns = ['Period0','Period1','Period2','...
<p>You can try maintaining a dictionary of dataframes</p> <pre><code>import pandas as pd tickers = ['AMZN','AAPL','MSFT','DIS','GOOG'] column_names = ['Period0','Period1','Period2','Period3'] ticker_dfs ={} for index, ticker in enumerate(tickers): bs_index = 'BS' + str(index) is_index = 'IS' + str(index) ...
python|pandas|loops|finance|yfinance
0
357,557
73,519,834
#I whish I could remember pi
<p>I tried running a loop to estimate pi. this is using a geometrical estimation by Archimedes stating the perimeter of any (convex) polygon inscribed in a circle is less than the circumference of the circle, which, in turn, is less than the perimeter of any circumscribed polygon. the code goes like this:</p> <pre><cod...
<p>You forgot to update <code>beta</code>, it should be done in the loop as <code>n</code> changes for each iteration:</p> <pre><code>import numpy as np D = 1 n = 10.0 S1 = 2 S2 = 5 while np.abs(S2-S1) &gt; 1e-6: beta = np.deg2rad(360/n) S1 = n * D * np.sin(beta/2) S2 = n * D * np.tan(b...
python|windows|numpy|jupyter-lab
1
357,558
73,442,454
Understanding the logic of using the any() arguement
<p>I have a dataframe that contains only 1s and 0s and looks like this (in reality I have several more columns):</p> <pre><code>Test A B C D E 0 1 1 0 1 0 0 0 1 0 1 0 0 0 0 0 1 0 1 1 0 1 1 0 </code></pre> <p>I first look at just the first column and check each row to return True if there is a one and False ...
<p>The problem is that you started your column slicing at 1 instead of 0, you are skipping the <code>test</code> column.</p> <p><code>df.iloc[:,0:1+i].any(axis=1)</code> (notice it starts at 0 now)</p> <p>This small correction should make it works as intended.</p>
python|pandas
4
357,559
73,507,545
Create dataframe from dictionary with column names
<p>I'm attempting to create a dataframe with dictionary keys and values in two different columns then name then name the columns with string names</p> <p>Here is my dictionary:</p> <pre><code>my_dict = {'amd_0': 102, 'amd_3': 11} </code></pre> <p>Column names:</p> <pre><code>columns = ['column1', column2'] </code></pre...
<p>You can create a dataframe using the dictionary items and specify the <code>columns</code> list as the columns:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame(my_dict.items(), columns=columns) df </code></pre> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th>c...
python|pandas
3
357,560
73,179,836
tensorflow.py_function fails to temporarily switch to eager execution while in graph mode
<p>I'm not sure if this is a Tensorflow bug or my misunderstanding about what this function is supposed to do, but I can't get <code>tf.py_function</code> to return an <code>EagerTensor</code> <em>while in graph mode</em>. Consequently, calling <code>.numpy()</code> on the output of this function fails.</p> <p>The issu...
<h4>Solution 1 (with eager execution):</h4> <p>In Tensorflow 2, eager execution should be enabled by default.</p> <p>I reproduced the exact same code as the Tensorflow tutorial without any problem (the assertion does not generate errors). I used Colab under Tensorflow 2.8.2 and Python 3.7.13.</p> <p>If you have problem...
python|tensorflow|eager-execution
1
357,561
73,196,573
pandas pivot table with unique values of columns
<p>I have df with some string values.</p> <pre><code>so = pd.DataFrame({ &quot;col1&quot;: [&quot;row0&quot;, &quot;row1&quot;, &quot;row2&quot;], &quot;col2&quot;: [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;], &quot;col3&quot;: [&quot;A&quot;, &quot;A&quot;, &quot;B&quot;], &quot;col4&quot;: [&quot;B&quot;, &quot;A&...
<p><code>melt</code> and <code>crosstab</code>:</p> <pre><code>df2 = so.melt('col1') pd.crosstab(df2['col1'], df2['value']) </code></pre> <p>or <code>melt</code> and <code>groupby.count</code>:</p> <pre><code>so.melt('col1').groupby(['col1', 'value']).size().unstack(fill_value=0) </code></pre> <p>output:</p> <pre><code...
python|python-3.x|pandas|dataframe|pivot
1
357,562
73,457,842
osisoft piconfig export csv into regular pandas DF
<p>I have some issues trying to import csv files from osisoft piconfig export into regular pandas DF.</p> <p>I am a beginner in Python, so if you are kind enough to answer me, I kindly ask you to explain in details if possible.</p> <p>The raw data looks like this:</p> <pre><code>&quot;*&gt; sensor_1&quot;,&quot; 09-aug...
<p>I would try to first format my raw data, then create a dataframe with the filtered data. For example the following code creates a csv file from your raw data:</p> <pre><code>import csv f = open('output.csv', 'w') writer = csv.writer(f) with open('test.csv', 'r') as file: data = file.read().rstrip() split_da...
python|pandas|dataframe|csv|osisoft
0
357,563
73,201,999
Inserting a dataframe row into another dataframe using the name of the index value
<p>Basically the middle image shows the current values after all iterations are complete. I tried many ways to try to update the index &quot;0&quot; to be the particular ConfigurationLevel_ value e.g. CongigurationLevel_1 but I have had no success. While I'm able to create a dataframe with the correct index values, I'm...
<p>Instead of creating a dataframe with the index names initially create the basic dataframe without indexes:</p> <pre><code>Combined_SHAP_df = pd.DataFrame() </code></pre> <p>and after the dataframe has been completely filled with values, ie. after the loop containing:</p> <pre><code>Combined_SHAP_df = pd.concat([Comb...
python-3.x|pandas|dataframe
0
357,564
73,214,320
Delete rows with a 'LIKE' pattern (not an exact pattern) in Python
<p>I have a dataset where I would like to remove all rows that contain data with a certain pattern.</p> <p><strong>Data</strong></p> <pre><code>ID Date Stat AA Q1.22 ok CC Q2.22 yes CC Q1.23 ok CC Q1.24 no </code></pre> <p><strong>Desired</strong></p> <pre><code>ID Date Stat CC Q1.24 no ...
<p>it is very easy. use from regex method.</p> <p>pandas.Series.str.findall()</p> <p>pandas.Series.str.find()</p>
python|pandas|numpy
0
357,565
73,502,820
Converting DF to GDF - MultiLineString
<p>I have a <code>pandas.core.frame.DataFrame</code> with many attributes. I would like to convert the DF to a GDF and export as a geojson. I have columns <code>'geometry.type'</code> and <code>'geometry.coordinates'</code> - both are <code>pandas.core.series.Series</code>. An example exerpt is below - note that <code>...
<p>Taking your previous question as well</p> <ul> <li><strong>pandas</strong> <code>json_normalize()</code> can be used to create a dataframe from the JSON source. This also expands out the nested <strong>dict</strong>s</li> <li>it's then a simple case of selecting out columns you want as properties (have renamed as we...
python|pandas|geojson|geopandas
0
357,566
73,427,971
Need to melt DataFrame using timedelta and add column with a date
<p>I have done the opposite of this many times with groupby and pd.pivot_table, and have been successful in using pd.melt but do not know if this is the case for that and how to weave in the datetime component.</p> <p>original DF:</p> <pre><code>Location Week Starting Allotment A 8/01/2022 700 A ...
<p>You want to upsample, for this you can create all the dates and <code>explode</code>:</p> <pre><code>out = (df .assign(Day=[pd.date_range(d, periods=7, freq='D') for d in df['Week Starting']], Allotment=df['Allotment'].div(7) ) .explode('Day') ) </code></pre> <p>output (fir...
python|pandas
0
357,567
73,316,778
Update cell values of a big pandas dataframe
<p>I have a dataframe with 7K columns and and same 7K values as indices</p> <p>ex.</p> <pre><code> c1 c2 .... c7000 c1 c2 . . . c7000 </code></pre> <p>I want to update each cell of this dataframe on some condition.</p> <p>Can anyone please suggest f...
<p>Without knowing more about the question it is hard to give an answer. Please be more specific and ideally provide code to reproduce part of the dataframe that you are working with.</p> <p>Usually <code>apply()</code> is used in such cases if I understand your description correctly:</p> <pre><code>df[&quot;update&quo...
pandas|dataframe|accelerate
0
357,568
73,230,916
Python Pandas - Split on delimiter and append to new row
<p>I am trying to find a method in Pandas to automate the cleaning of some source data that is delimited by a comma. There are a range of columns that are delimited by a comma, however there are also columns that are not delimited by anything. I need a method to split the delimited cells that are delimited, and append ...
<p>You need to use the Explode function:</p> <pre><code>df.explode(['Name','Purchase Year','SKU']) </code></pre> <p>Use the column names that should be splitted</p>
python|pandas|dataframe
1
357,569
73,405,311
Skip file if value is not in data using python
<p>With my current code, I am trying to skip a csv file if it does not contain a value within the actual data that I am looking for.</p> <p>basically if it has &quot;PROD_NAME&quot; as a column, then it looks for that string and replaces it with the second string in that statement, but the first file in my folder does ...
<p>Could you just add an if statement before your transformation</p> <pre><code>if 'PROD_NAME' in df1.columns: df1.loc[df1['PROD_NAME'].str.contains('NA_NRF'), 'PROD_NAME'] = 'FA_GUAR' file_count += 1 # count the fil </code></pre>
python|pandas|dataframe|csv
2
357,570
73,481,092
How to pull values from JSON into pandas dataframe using a string as the index value
<p>I am looking to build a dataframe utilizing certain data from a JSON with multiple nested dictionaries.</p> <p>An example of the format of the JSON is as follows:</p> <pre><code>&quot;leagueYear&quot;: &quot;2021&quot;, &quot;stats&quot;: { &quot;Cincinnati Bengals&quot;: { &quot;offense&quot...
<p>You should probably look at <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.json_normalize.html" rel="nofollow noreferrer"><code>pd.json_normalize</code></a> before trying to reinvent the wheel:</p> <pre><code>data = {'leagueYear': '2021', 'stats': {'Cincinnati Bengals': {'offense': {'firs...
python|json|pandas|dataframe
1
357,571
73,510,959
Replace na in output with zeroes in pandas python
<p>I wanted to replace the 'na' value in the output with 0.0. Those are not NaN values. It had 'na' value in the csv file. I tried every method I thought I could to replace na with 0.0 but to no avail. Here is the output:</p> <pre><code> Brunei Darussalam Indonesia Malaysia Philippines Thailand Vie...
<p>Since you are reading CSV file, you can directly pass <code>na</code> to <code>na_values</code> parameter of <code>read_csv</code> function (currently you are passing <code>0.0</code>), then you can call <code>fillna(0)</code> either for entire dataframe, or for the columns of your choice:</p> <pre class="lang-py pr...
python|pandas|dataframe
3
357,572
73,355,151
Quickly ranking rows in very large dataframes
<p>So I have a very large dataframe with over 500 rows and 100 columns involved, each row representing a person and column representing a performance metric:</p> <pre><code>[Person] [Metric 1] [Metric 2] ... A [num] [num] B [num] [num] C [num] [num] D [num] ...
<p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.rank.html" rel="nofollow noreferrer"><code>pd.DataFrame.rank</code></a>:</p> <pre><code>out = (df .join(df.filter(like='Metric') .rank() .add_prefix('rank_') ) .sort_index(axis=1, key=lambda x: x.str.ex...
python|pandas|dataframe
1
357,573
73,432,561
How to fill empty data with zeros?
<p>After going through some previous answers I found that I could use this code to fill missing values of df1[0] which range from 340 to 515,</p> <pre><code>with open('contactasortedtest.dat', 'r') as f: text = [line.split() for line in f] def replace_missing(df1 , Ids ): missing = np.setdiff1d(Ids,df1[1]) ...
<p>You can use <code>df['x'].fillna(0)</code> to fill non zeros in a column</p>
python|pandas|numpy|set-difference
2
357,574
73,309,069
Define partition for window operation using Pyspark.pandas
<p>I am trying to learn how to use <code>pyspark.pandas</code> and I am coming across an issue that I don't know how to solve. I have a <code>df</code> of about 700k rows and 7 columns. Here is a sample of my data:</p> <pre><code>import pyspark.pandas as ps import pandas as pd data = {'Region': ['Africa','Africa','Afr...
<p>For Koalas, the repartition seems to only take in a number of partitions here: <a href="https://koalas.readthedocs.io/en/latest/reference/api/databricks.koalas.DataFrame.spark.repartition.html" rel="nofollow noreferrer">https://koalas.readthedocs.io/en/latest/reference/api/databricks.koalas.DataFrame.spark.repartiti...
python|pandas|dataframe|apache-spark|pyspark
0
357,575
73,282,103
Trying to read a directory of .xlsm files in pandas
<p>I (a noob) am currently trying to read a directory of .xlsm files into a pandas dataframe, with the intention of merging them all together into one big file. I've done similar tasks in the past with .csv files and had no problems, but this has me at a loss.</p> <p>I'm currently running this:</p> <pre><code>import pa...
<p>Please delete the encryption of the file.</p> <blockquote> <p>engine=&quot;openpyxl&quot;</p> </blockquote> <p>This does not support reading encrypted files.</p>
python|excel|pandas|visual-studio-code|xlsm
0
357,576
73,294,630
ValueError: Invalid fill method. Expecting pad (ffill) or backfill (bfill). Got nearest
<p>I have this df:</p> <pre><code> Week U.S. 30 yr FRM U.S. 15 yr FRM 0 2014-12-31 3.87 3.15 1 2015-01-01 NaN NaN 2 2015-01-02 NaN NaN 3 2015-01-03 NaN NaN 4 2015-01-04 NaN NaN ... ... ... ... 2769 ...
<p>It may not work great with date columns, but it works well with a datetime index, which is probably what you should be using here:</p> <pre><code>df = df.set_index('Week') df = df.interpolate(method='nearest') print(df) # Output: U.S. 30 yr FRM U.S. 15 yr FRM Week 2014-12-31 3.87 ...
python|pandas|dataframe|interpolation|valueerror
1
357,577
73,433,266
Matplotlip plot barchart of grouped data increase space of x-axis
<p>I want to make a barchart out of gourped data, but I cannot get a space between the columns on x-axis. I tried to set different figure size and width set to 0.8 , but this does not help.</p> <p>My code looks like this:</p> <pre><code>data = [['Tom', 'a'], ['Tom', 'a'],['nick', 'a'], ['juli', 'a'],['juli', 'a'],['jul...
<p>Changing the width of the individual bars in a group isn't currently supported. It also could be quite confusing to know which bars belong to the same group, especially with empty bars involved.</p> <p>A simple workaround could be to set the edgecolor to <code>ec='white'</code> (and <code>lw=1</code>).</p> <p>Or you...
python|pandas|dataframe|matplotlib|bar-chart
1
357,578
73,486,252
Iterate over multiple columns and replace the values in these columns after a row (increment) with null values
<p>Given a dataframe <code>df</code> as follows:</p> <pre><code> date value 20211003 20211010 20211017 0 2021-9-19 3613.9663 NaN NaN NaN 1 2021-9-26 3613.0673 NaN NaN NaN 2 2021-10-3 3568.1668 NaN NaN ...
<p>Option 1:</p> <pre><code>a = df.iloc[:, 2:].apply(lambda x:x.dropna().head(3)) df.iloc[df.index &lt;= a.index.max(),:2].join(a) </code></pre> <p>Out:</p> <pre><code> date value 20211003 20211010 20211017 0 2021-9-19 3613.9663 NaN NaN NaN 1 2021-9-26 3613.0673 ...
python|python-3.x|pandas|dataframe
1
357,579
73,501,667
Remove duplicated from Pandas dataframe based on other columns
<p>I am working on a Pandas grouped dataset which looks like below:</p> <pre><code>test_identifier timestamp Count_of_Fail_tests test_status test1 22-08-2022 07:00 0 pass 23-08-2022 07:00 0 pass 24-08-2022 07:00 0 pass 25-08-2022 07:00 0 pass 26-08-2022 07:00 0...
<p>This should give you the desired results. It will hid all the &quot;passes&quot; from your df and only count the fails per date/test paring</p> <pre><code>df.mask(df['test_status'].eq('pass')).groupby(['timestamp', 'test_identifier'], as_index = False)['test_status'].count() </code></pre>
python|pandas|dataframe
0
357,580
73,295,016
Pandas: Creation of a new DataFrame if with values contained in two others
<p>I have two Pandas Dataframes and would like to create a new DataFrame. The DataFrames look like this:</p> <pre><code> DataFrame 1 DataFrame 2 |Datetime |Val k |Val m | |Datetime |Val x| |-----------------------|---------|---...
<p>There are a couple of options to do this kind of tasks:</p> <ul> <li>slice the first table <code>df1</code> based on the second table <code>df2</code> (so you basically create a boolean vector)</li> <li><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html" rel="nofollow nor...
python|pandas
1
357,581
73,450,888
Can't remove space from value in pandas DataFrame
<p>These are the values in my DataFrame</p> <p><a href="https://i.stack.imgur.com/72hvT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/72hvT.png" alt="enter image description here" /></a></p> <p>What I am trying to do, is to change the datatype of columns from string to float, but I can't because so...
<p>This code should work:</p> <pre><code>df['Value'] = df['Value'].astype(str).str.replace(' ','').astype(float) </code></pre> <p>If it does not, try to troubleshoot with the following:</p> <pre><code>def check_cell(x): try: x = float(str(x).replace(' ', '')) return x except: print(x) ...
python|pandas
1
357,582
73,401,526
Error when converting int to numpy array?
<p>I encounter the following errors when converting an integer to a numpy array:</p> <pre><code>a = 150 b = np.array(a) b[0] *** IndexError: too many indices for array: array is 0-dimensional, but 1 were indexed </code></pre> <p>I expect the output of <code>b[0]</code> is <code>150</code>, but get the IndexError. Why?...
<p>You have in effect created a scalar or zero dimensional array.</p> <p>If you need to index into this, try</p> <pre><code>b = np.array([a]) </code></pre>
numpy
2
357,583
73,366,027
writing embedded loops in seaborn to make histograms in separate windows and setting plot titles to column names
<p>I'm trying to make histograms for PM2.5/PM10 ratios for 24 hour average data for around 50 sites and want the histograms to be in separate windows. I have a code that works, but it automatically sets the x-axis label as the site name. I figured out how to change the x labels but am having trouble writing a loop that...
<p>I figured it out - I added this line of code to the loop and it worked:</p> <pre><code>plt.title(pmf.columns[i]) </code></pre>
pandas|for-loop|seaborn|nested-loops
0
357,584
73,246,098
How to add columns to pandas df where grouped values are counted for ordered plotting of categories
<p>I build a plotly dashboard in python that displays multiple variables over time. One of the variables is here called &quot;color&quot; and I would like to sort the resulting plot by it.</p> <pre><code>import pandas as pd import plotly.express as px import string import random import numpy as np # for the color mapp...
<h2>How to get color count values into their columns</h2> <p>Let's add the number of colors per letter:</p> <pre><code>color_counts = ( df.groupby('letters')['colors'] .value_counts() .unstack(fill_value=0) ) df = df.merge(color_counts, on='letters') </code></pre> <p>The first 5 records of the modified data...
pandas|plotly
6
357,585
73,390,091
Pandas - Calculate the Average of the Same data
<p>I have a pandas df that has a list of item numbers and then a number next to it. I would like to somehow get the average of all the same item numbers and that number next to it.</p> <p>Here is a part of the DataFrame:</p> <pre><code>Item ID Time X32TR2639 7.142857 X32TR2639 7.142857 X36SL7708 1...
<p>I would propose a straightforward <code>groupby.mean</code> and a <code>reset_index</code>.</p> <pre><code>data = {&quot;Item ID&quot;:['X32TR2639','X32TR2639','X36SL7708','X36TA0029','X36TR3016'],'time':[7.142857,7.142857,16.714286,16.714286,16.714286]} df = pd.DataFrame(data) df.groupby('Item ID').mean().reset_i...
python|pandas|dataframe
5
357,586
73,317,676
ImportError: /usr/lib/aarch64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.30' not found
<p>I install the kneed package in linux aarch64 architecture in <strong>miniconda3</strong>. When I import kneed inside python, I got the following error</p> <pre><code> import kneed Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; File &quot;/home/su/miniconda3/envs/myen...
<p>Install gcc 12.1 via conda like this:</p> <pre class="lang-bash prettyprint-override"><code>conda install gcc=12.1.0 </code></pre> <p>Ensure that its libraries are in the library search path by setting the appropriate environment variable:</p> <pre class="lang-bash prettyprint-override"><code>export LD_LIBRARY_PATH=...
python|numpy|tensorflow
0
357,587
35,300,159
How to set marker style of Dataframe plot in Python Pandas?
<p>I used df.plot() to get this plot:</p> <p><a href="https://i.stack.imgur.com/D3hCD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/D3hCD.png" alt="enter image description here" /></a></p> <p>I want to change the marker style to circles to make my plot look like this:</p> <p><a href="https://i.stac...
<p>The marker is pretty easy. Just use <code>df.plot(marker='o')</code>.</p> <p>Adding the y axis value above the points is a bit more difficult, as you'll need to use matplotlib directly, and add the points manually. The following is an example of how to do this:</p> <pre><code>import numpy as np import pandas as pd...
python|pandas
18
357,588
35,157,650
Smooth surface Plot with Pyplot
<p>My question is almost similar to this on: <a href="https://stackoverflow.com/questions/20848740/smoothing-surface-plot-from-matrix">smoothing surface plot from matrix</a></p> <p>only that my toolset is matplotlib and numpy (so far).</p> <p>I have sucessfully generated a X, Y and Z-grid to plot with</p> <pre><code...
<p>From the link you suggested, the example <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/tutorial/interpolate.html#two-dimensional-spline-representation-procedural-bisplrep" rel="noreferrer">here</a> is probably closest to what you want. You can use the example with your values,</p> <pre><code>import nump...
python|numpy|matplotlib
17
357,589
35,232,507
Is there a better way to collect unique index values in pandas?
<p>I've got some data that looks like this:</p> <pre><code>&gt;&gt;&gt; print totals.sample(4) start end \ time region_type 2016-01-24 02:17:10.238 STACK GUARD 79940452352 79940665344 2016-...
<p>Use <code>index.get_level_values</code> (which returns the values used), not <code>index.levels</code> (which returns the values the index knows about):</p> <pre><code>mask = totals['dirty']+totals['swap'] &gt; 1e7 result = mask.loc[mask] region_types = result.index.get_level_values('region_type').unique() </code><...
python|pandas
2
357,590
34,955,321
Pandas: Compress Column Names to Cell Values where True
<p>I have a dataframe that looks like</p> <pre><code>ID Cat1 Cat2 Cat3 Cat4 3432432 True False True False 1242323 False True False False 3423883 False False False True </code></pre> <p>How can I convert that to a dataframe that chooses the first column that is True?</p> <pre><c...
<p>You could take advantage of the fact that <code>idxmax</code> will return the first True:</p> <pre><code>&gt;&gt;&gt; df.set_index("ID").idxmax(axis=1).reset_index(name="Status") ID Status 0 3432432 Cat1 1 1242323 Cat2 2 3423883 Cat4 </code></pre> <p>which works because we have</p> <pre><code>&gt...
python|pandas|dataframe
8
357,591
35,104,926
Split a column into 3 columns in pandas
<p>I have a column called <code>Names</code> which looks like this, I need to compare it other column in a different panda dataframe which has the last name and first name but not the initials like this one. I am trying to split the initials out of the column in a new column, using space as delimiter, but will probably...
<p>Use the vectorised <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="noreferrer"><code>str.split</code></a> with <code>expand=True</code>, this will unpack the list into the new cols:</p> <pre><code>In [17]: df[['lastname', 'firstname', 'middle initial']] = df['name']...
string|pandas|split|dataframe|multiple-columns
8
357,592
35,208,628
Store indices of neighbouring cells which fall within a certain radius
<p>I have a very large numpy array of 1s and 0s. I want to go row by row and look for all the 1s. Once I encounter a 1, I want to store the indices of entries which fall inside a radius of five rows. This is better illustrated in the picture: </p> <p><a href="https://i.stack.imgur.com/PAXVd.png" rel="nofollow noreferr...
<p>The operation you are describing is called <a href="https://en.wikipedia.org/wiki/Dilation_%28morphology%29" rel="nofollow noreferrer">dilation</a>. I you have scipy, you could use <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.morphology.binary_dilation.html" rel="nofollow norefer...
python|arrays|numpy
2
357,593
35,328,168
Output array after performing fast fast fourier transform of a data set
<p>I'm trying to perform a fourier transform of a data set that I have and subsequently writing its real and imaginary parts separately.</p> <p>This is my code:</p> <pre><code>import sys,string import numpy as np from math import * import fileinput from scipy.fftpack import fft, ifft temparray = [] for i in range(2...
<p>As others have indicated, include a modified version of </p> <pre><code>&gt;&gt;&gt; np.set_printoptions(edgeitems=5,linewidth=80,precision=2,suppress=True,threshold=10) &gt;&gt;&gt; a = np.arange(0,100.) &gt;&gt;&gt; &gt;&gt;&gt; a array([ 0., 1., 2., 3., 4., ..., 95., 96., 97., 98., 99.]) &gt;&gt;...
python|numpy|fft
2
357,594
35,295,089
Rehaspe a 2D matrix into a 3D ? (x, y) -> (x/72,72,y)
<p>I have a <a href="http://pastebin.com/7hzUpFrU" rel="nofollow">text file</a> from which I load the original matrix.</p> <p>The text file has comments with # and it basically has multiple matrices of 77*44.</p> <p>I would like to read this file and store each matrix from this complete number of mats.</p> <pre><cod...
<p>Use <code>x.reshape(-1, 72, 44)</code>:</p> <pre><code>In [146]: x = np.loadtxt('data' ,dtype=np.uint8, comments='#', delimiter='\t') In [147]: x = x.reshape(-1, 72, 44) In [148]: x.shape Out[148]: (34, 72, 44) </code></pre> <p>When you specify one of the dimensions as -1, <code>np.reshape</code> replaces the -1...
python-2.7|numpy|matrix|reshape
1
357,595
35,047,172
Record Array to json.dumps
<p>I need to generate a json from a Pandas DataFrame, but using df.to_json shows segmentation error, so I want to find another way to create the json and the only thing I got was to create a records array from the dataframe.</p> <p>Now I need to create the json.dumps with the names of the files. Something like this</p...
<p>Like the error says, <code>d</code> is a list, which you are trying to index with unicode strings. You have to change this to a dictionary (<code>d = {}</code>).</p> <p>However, the output still wouldn't be what you'd expect. Instead you can do this:</p> <pre><code>for r in data2: arrayJSON.append(dict(zip(col...
python|json|numpy|pandas|dump
0
357,596
35,211,774
Merging dataframes based on Time
<p>I've data from two different weather stations for a location. One station was installed during the 80s and the other station installed during the mid 90s. Due to instrumental error the readings got unreliable for the old station. And there are several instances of missing records for the new station too.</p> <p>I p...
<p>Try combine_first().</p> <pre><code>import numpy as np import pandas as pd from pandas.tseries.offsets import DateOffset df_new =pd.DataFrame( {'Date': {0: '01/01/1994', 1: '01/02/1994', 2: '01/03/1994', 3: '01/04/1994'}, 'Rain': {0: 0, 1: 0, 2: 0, 3: 0}, 'TMAX': {0: -5.5, 1: np.nan, 2: -1.5, 3: np.nan}, 'TMIN'...
python|pandas|merge
2
357,597
35,101,195
append the data in python
<p>I have one csv file like this</p> <pre><code>out.csv seedProductId,relatedProducts </code></pre> <p>My output is in dftype object looks like this</p> <pre><code>100A7E54111FB143 100D11CF822BBBDB 1014120EE9CCB1E0 10276825CD5B4A26 10364F56076B46B7 103D1DDAD3064A66 103F4F66EEB54308 </code...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.cat.html" rel="nofollow"><code>cat</code></a> for merging data, then create new <code>Series</code> for each columns and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code...
python|pandas|dataframe
1
357,598
30,889,422
How to use custom data structure with multiprocessing in python
<p>I'm using python 2.7 and numpy on a linux machine. I am running a program which involves a time-consuming function <code>computeGP(level, grid)</code> which takes input in form of a numpy array <code>level</code> and an object <code>grid</code>, which is not is not modified by this function.</p> <p>My goal is to pa...
<p>This SO question is very similar to yours: <a href="https://stackoverflow.com/questions/17785275/share-large-read-only-numpy-array-between-multiprocessing-processes">Share Large, Read-Only Numpy Array Between Multiprocessing Processes</a></p> <p>There are a few answers in there, but the simplest <em>if you are only...
python|python-2.7|numpy|data-structures|multiprocessing
0
357,599
31,004,458
Dropping Dataframe rows based on name
<p>I have the following dataframe <code>df</code> where I am trying to drop all rows having <code>curv_typ</code> as <code>PYC_RT</code> or <code>YCIF_RT</code>. </p> <pre><code> curv_typ maturity bonds 2015M06D19 2015M06D18 2015M06D17 \ 0 PYC_RT Y1 GBAAA -0.24 -0.25 -0...
<p>You need to assign the resulting <code>DataFrame</code> to the original <code>DataFrame</code> (thus, over-writing it):</p> <pre><code>df = df[df["curv_typ"] != "PYC_RT"] df = df[df["curv_typ"] != "YCIF_RT"] </code></pre>
python|pandas
1