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
355,900
47,582,212
tensorflow dbg error: Encode method is not implemented for DatasetVariantWrapper objects
<p>I'm new to debugging a Tensorflow code. Following the <a href="https://www.tensorflow.org/programmers_guide/debugger" rel="nofollow noreferrer">instruction</a>, I installed <code>pyreadline</code> and ran my Tensorflow code with <code>--debug</code> option. </p> <pre><code>tfdbg&gt; run -f has_inf_or_nan 2017-11-3...
<p>Maybe the file path is too long, Windows limits <strong>max path length</strong>, try</p> <pre><code>sess = tf_debug.LocalCLIDebugWrapperSession(sess, dump_root='L:\debug_tmp') </code></pre>
debugging|tensorflow
0
355,901
47,721,464
Numpy array creation using a sequence
<p>I have seen <a href="https://stackoverflow.com/questions/10753528/numpy-array-creating-with-a-sequence?noredirect=1&amp;lq=1">this</a>, but it doesn't quite answer my question.</p> <p>I have an array:</p> <pre><code>x = np.array([0, 1, 2]) </code></pre> <p>I want this:</p> <pre><code>y = np.array([[0,1], [0,2], ...
<p><strong>Approach #1 :</strong> One approach would be -</p> <pre><code>x[np.argwhere(~np.eye(len(x),dtype=bool))] </code></pre> <p><strong>Approach #2 :</strong> In two steps -</p> <pre><code>r = np.arange(len(x)) out = x[np.argwhere(r[:,None]!=r)] </code></pre> <p><strong>Approach #3 :</strong> For performance, ...
python|arrays|numpy
1
355,902
47,583,920
How to use early stopping for training deep neural network in TensorFlow 1.4?
<p>From some moment in the training process of a convolutional neural network, the cost function is not getting better. I want to define the condition to stop the training. I have found one solution using <a href="https://www.tensorflow.org/versions/r1.1/get_started/monitors" rel="nofollow noreferrer">ValidationMonitor...
<p>Since <code>ValidationMonitor</code> doesn't work well with distributed training, We decided not to implement it as a Hook. We're waiting for a distributed friendly version of it.</p> <p>As a workaround you can wrap <code>ValidationMonitor</code> as a hook. Following code shows how to do it: <code> validation_hook ...
tensorflow|deep-learning|conv-neural-network
0
355,903
47,888,641
tensorflow comparing each element of a tensor
<p>My input Tensor has size of <code>3x5</code>. I tried to get the total number of each tensor with values more than 1. For example:</p> <pre><code>input list[[0.1 , 1.1 , 1.3, 1.5 , 0.7] , [1.1 , 1.1 , 0.8, 1.5 , 0.7] , [0.1 , 0.0 , 1.3, 0.5 , 1.7]] return[[3],[3],[2]] </code></pre> <p>be...
<p>This returns</p> <blockquote> <p>[3 3 2]</p> </blockquote> <pre><code>import tensorflow as tf inputlist = [[0.1 , 1.1 , 1.3, 1.5 , 0.7] , [1.1 , 1.1 , 0.8, 1.5 , 0.7] , [0.1 , 0.0 , 1.3, 0.5 , 1.7]] x = tf.Variable(initial_value=inputlist) sess = tf.Session() sess.run(tf.global_variables...
tensorflow|compare
0
355,904
47,833,499
Adding rows to a Dataframe to unify the length of groups
<p>I would like to add element to specific groups in a Pandas DataFrame in a selective way. In particular, I would like to add zeros so that all groups have the same number of elements. The following is a simple example:</p> <pre><code>import pandas as pd df = pd.DataFrame([[1,1], [2,2], [1,3], [2,4], [2,5]], columns=...
<p>You can create new level of <code>MultiIndex</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>cumcount</code></a> and then add missing values by <code>unstack/stack</code> or <code>reindex</code>:</p> <pre><code>df = ...
python|pandas|dataframe|group-by|autofill
1
355,905
47,829,141
Plotting data from a Pandas Dataframe with distinct curves based on column values
<p>I have a Pandas dataframe which looks like this:</p> <pre><code>City timestamp HUMI year Beijing 10100 43.0 2010 Chengdu 10100 81.2 2010 Beijing 10101 47.0 2010 Chengdu 10101 86.99 2010 Beijing 10102 43.0 2010 Chengdu 10102 86.99 2010 Beijing 10103 5...
<p>It seems you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html" rel="nofollow noreferrer"><code>pivot</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html" rel="nofollow noreferrer"><code>plot</code></a>:</p> <pre><co...
python|pandas|plot
2
355,906
47,934,715
Python3 Scipy: Desired error not necessarily achieved due to precision loss
<p>I'm implementing Andrew Ng's Coursera course in Python and I'm doing Ex2 right now, Logistic Regression. I'm trying to use SciPy's optimize.minimize but I can't seem to get it to run correctly. I'll try to give as brief a summary of my code as possible while being thorough. I'm using Python3. Here is my variable...
<p>If anyone stumbles across this and happens to have the same problem, I figured out that in my sigmoid function I should have had</p> <pre><code>return 1/(1 + np.exp(-x)) </code></pre> <p>but had</p> <pre><code>return 1/(1 + np.exp(x)) </code></pre> <p>After fixing that, the minimize function converged normally.<...
python|python-3.x|numpy|scipy
3
355,907
47,829,357
Pandas groupby: 3 max per period among multiple columns
<p>I have these data:</p> <pre><code> val1 val2 val3 dt 2017-12-15 00:00:00 81 90 79 2017-12-15 00:01:00 67 85 80 2017-12-15 00:02:00 4 41 37 2017-12-15 00:03:00 61 68 29 2017-12-15 00:04:00 49 6 56 2017-12-15 00:05...
<p>Since it doesn't matter where your values come from, let's reshape your data a bit.</p> <pre><code>df = df.reset_index().melt('dt').drop('variable', 1) df.head(10) dt value 0 2017-12-15 00:00:00 81 1 2017-12-15 00:01:00 67 2 2017-12-15 00:02:00 4 3 2017-12-15 00:03:00 61 4 2017...
python|pandas|dataframe|group-by|pandas-groupby
1
355,908
47,980,642
Getting `FailedPreconditionError: Attempting to use uninitialized value Variable` Error while initializing variables in tensor flow
<p>While I'm trying to initialize the variable in tensor flow, I'm getting above exception. Below is the code. Can someone help on this?</p> <pre><code>import tensorflow as tf node1 = tf.constant(3.0, dtype=tf.float32) node2 = tf.constant(4.0) # also tf.float32 implicitly print(node1, node2) init_g = tf.global_var...
<p>This happens to me when I initialize the global variables and creating new variables / operations after</p> <p>try this</p> <pre><code> import tensorflow as tf node1 = tf.constant(3.0, dtype=tf.float32) node2 = tf.constant(4.0) # also tf.float32 implicitly node3 = tf.add(node1, node2) node4 = t...
python-3.x|tensorflow
2
355,909
47,712,295
How to Sanitise CSV
<p>I have a raw csv from which I am creating a dataframe to do so some data cleaning and then convert it back to csv. But the final output I am getting is not in a proper format. so I wanted to know the way on how I can sanitize the csv.</p> <p>For example I have the raw csv in the form:</p> <pre><code>id,text,value ...
<p>I'm not exactly sure what you mean by proper format as your first csv is already in csv form. But to fill your <code>na</code> results, you can do this:</p> <pre><code>df.fillna('0') </code></pre>
python|pandas|csv
2
355,910
47,783,597
Safe and most efficient way to get the column number of sliced pandas dataframes in python
<p>I have a function with an argument that can accept a pandas dataframe or some columns of a dataframe. When I pass a single column the shape is e.g. df.shape=(10,) and therefore trying to get the number of columns with df.shape[1] throws an error. </p> <p>I found a solution by using a ternary statement, but is there...
<p>I would do it this way:</p> <pre><code>def number_of_cols(input): try: return input.shape[1] except IndexError: return 1 </code></pre> <p>Usage:</p> <pre><code>In [63]: number_of_cols(df['A']) Out[63]: 1 In [64]: number_of_cols(df) Out[64]: 2 </code></pre>
python|pandas|numpy
0
355,911
47,588,594
Unexpected result from DataFrame.groupby() and max()
<p>Let say I have a CSV of name, gender, and its count. </p> <p>I am looking for majority name by using groupby() and max(). But I found something strange from the result:</p> <p><strong>CSV:</strong></p> <pre><code>Name Gender Count Connie F 90 Connie F 78 Peter M 200 Connie M ...
<p>It is correct, because <code>M</code> > <code>F</code>, better explanation is <a href="https://stackoverflow.com/a/20463240/2901002">here</a>.</p> <p>Also I find <a href="https://github.com/pandas-dev/pandas/issues/2700#issuecomment-12346160" rel="nofollow noreferrer">this</a>, so <code>string</code> columns are no...
python|pandas|dataframe
1
355,912
47,775,067
how to assign the element of tensor from other tensor in tensorflow
<p>I want to assign tensor from other tensor. i will give simple demo as followed:</p> <pre><code>import tensorflow as tf input = tf.constant([1.,2.,3.],dtype=tf.float32) test = tf.zeros(shape=(3,),dtype = tf.float32) test[0] = input[0] #tf.assign(test[0],input[0]) with tf.Session() as sess: sess.run(test) <...
<p>Only Variables support sliced assignment, while <code>tf.zeros</code> creates a constant Value tensor; You need to declare <code>test</code> as a variable:</p> <pre><code>sess = tf.Session() test = tf.Variable(tf.zeros(shape=(3,),dtype = tf.float32)) init_op = tf.global_variables_initializer() sess.run(init_op) se...
python|tensorflow
2
355,913
47,687,701
How to read two columns using python
<p>How to read two columns the first of which contains letters and the second of the values.</p> <pre><code>C0 -0.158040 C1 -0.157117 C2 -0.143805 C3 -0.140561 S4 0.059175 H5 0.128940 H6 0.129007 H7 0.142421 H8 0.139979 </code></pre> <p>I often used this script below (it w...
<p>You don't need any libraries at all, let alone pandas or re. Just read the file and use list comprehensions plus string methods to extract the data.</p> <pre><code>with open('file.csv', 'r') as f: data = f.readlines() oX = [line.replace('\n', '').split(',')[0] for line in data] oY = [float(line.replace('\n', '...
python|pandas|numpy
2
355,914
47,663,784
How to perform element-wise multiplication of two vectors having different dimensions
<p>I have two vectors A &amp; B having dimensions (1, 100) &amp; (784, 100) respectively. I thought A would be broadcast along the raw to the same dimension as B, but got error that "Dimensions must be equal". Can you please explain why?</p>
<p>Broadcasting of matrices with the same rank (i.e. <code>2</code>) seems to work as <a href="https://www.tensorflow.org/performance/xla/broadcasting" rel="nofollow noreferrer">it says on the tin</a>:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf tf.__version__ # 1.3.0 A = tf.constant([...
tensorflow
0
355,915
47,752,324
Matrix multiplication on 4D numpy arrays
<p>I need to perform matrix multiplication on two 4D arrays (m &amp; n) with dimensions of 2x2x2x2 and 2x3x2x2 for m &amp; n respectively, which should result in a 2x3x2x2 array. After a lot of research (mostly on this site) it seems this can be done efficiently with either <strong>np.einsum</strong> or <strong>np.ten...
<p>You could simply swap the axes on the <code>tensordot</code> result, so that we would still leverage <code>BLAS</code> based sum-reductions with <code>tensordot</code> -</p> <pre><code>np.tensordot(m,n, axes=((1,3),(0,2))).swapaxes(1,2) </code></pre> <p>Alternatively, we could swap the positions of <code>m</code> ...
python|arrays|numpy|matrix
3
355,916
47,821,107
pandas create a new column by comparing two dataframes
<p>I have two dataframes, df1 and df2.</p> <p>df1:</p> <pre><code>ID Label 1 a 2 b 5 c </code></pre> <p>df2:</p> <pre><code>ID 1 2 3 </code></pre> <p>I want to create a new column "label" in df2 by comparing the two dataframes. If the ids match, label in df2 should equal to label in df1. If the ...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow noreferrer"><code>map</code></a> and then replace <code>NaN</code>s with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.fillna.html" rel="nofollow noreferrer"><code>fillna</c...
python|pandas
2
355,917
47,636,049
Python pandas CustomBusinessDay
<p>I am attempting to filter some time series data without any luck in pandas.. Any tips for what I am doing wrong is greatly appreciated.. First I am attempting to filter just for the month of July 2013 and then filter the data again for taking hourly averages of the dataset samples.</p> <p>Ultimately what I am wanti...
<blockquote> <p>Ultimately what I am wanting to do is filter the data as described above in addition for Weekdays, OR individual weekdays Mondays, Tuesdays, Wednesday, etc. with the CustomBusinessDay function.</p> </blockquote> <p>Have you considered using <code>DatetimeIndex.dayofweek</code>?</p> <blockquote> ...
python|python-3.x|pandas|data-science
1
355,918
47,900,902
Tensorflow android demo got error. Fail to connect to camera service
<p>I tried to run <code>Tensorflow</code> demo for android. (<a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/android" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/android</a>) my phone is 22 API level. I run the demo followed by the...
<p>You might need to <strong>request the permission</strong> at runtime. See <a href="https://developer.android.com/training/permissions/requesting.html" rel="nofollow noreferrer">docs</a> for more information on this topic. Requesting runtime permissions is required when targeting Android 6.0 or later.</p>
android|tensorflow|camera
0
355,919
47,887,414
Matplotlib 3d surface plot input arrays
<p>I am trying to create a surface plot using 3 numpy arrays:</p> <ul> <li><code>x_deflections</code> [shape: (10,)]</li> <li><code>y_alphas</code> [shape: (12,)]</li> <li><code>z_height_at_target</code> [shape: (120,)]</li> </ul> <p><code>x_deflections</code> and <code>y_alphas</code> are given and <code>z_height_at...
<p>Solved this using @Uvar 's suggestion of transposing <code>z_height_at_target</code> and by putting the values in in 2 dimensions, instead of reshaping afterwards (This effectively does the same as the previous code):</p> <pre><code>i = 0 x_count = 0 miss_count = 0 for x in x_deflections: y_count = 0 for y ...
python|numpy|matplotlib
0
355,920
47,907,409
How to use the created CNN model with new data in Keras
<p>I just followed a tutorial that classifies 10k images of cats and dogs with CNN with Keras(Tensorflow backend).</p> <p>Everything seems OK, I obtained good accuracy on both test and training sets:</p> <pre><code>.... Epoch 24/25 250/250 [==============================] - 26s 104ms/step - loss: 0.2938 -...
<p>This should work. I like to use <code>skimage</code>, but that's up to you.</p> <pre><code>import skimage.io as io import skimage.transform as tr img = io.imread('img.jpg') # Reads the image img = tr.resize(img, (64, 64, 3)) # Resizes the image img = img[np.newaxis, ...] # Adds a new dim to simula...
python|tensorflow|keras|conv-neural-network
3
355,921
47,807,426
How to test which cell in a pandas dataframe string column contains a substring of a given reference string?
<p>I am dealing with a pandas dataframe that looks like this:</p> <pre><code>0 Item Category 1 Hammer A 2 Car A 3 Cardiologist B 4 Park A 5 Parkway A 6 CarparkCar A </code></pre> <p>I need to find all cells in <code>Item</code> that contain a specific sequence of letters, defined...
<p><strong>Option 1</strong><br> One simple way to do this is using <code>apply</code> + <code>set.issubset</code> - </p> <pre><code>v = df.Item.str.lower().apply(lambda x: set(x).issubset('carpark')) v 0 False 1 True 2 False 3 True 4 False 5 True Name: Item, dtype: bool </code></pre> <p>Assign ...
python|string|pandas|substring
3
355,922
47,583,146
Cursive Words not connecting in image
<p><a href="https://i.stack.imgur.com/0egNn.png" rel="nofollow noreferrer">OutPut Image</a> / <a href="https://i.stack.imgur.com/4Az1f.png" rel="nofollow noreferrer">Expected Image</a></p> <p>I am generating images for cursive scripts through font and its unicode but in output image characters are separate not joined...
<p>The docs say you should specify features. See <a href="http://pillow.readthedocs.io/en/4.2.x/reference/ImageDraw.html#PIL.ImageDraw.PIL.ImageDraw.Draw.text" rel="nofollow noreferrer">http://pillow.readthedocs.io/en/4.2.x/reference/ImageDraw.html#PIL.ImageDraw.PIL.ImageDraw.Draw.text</a></p> <pre><code>PIL.ImageDraw...
python|numpy|python-imaging-library|itertools|python-unicode
0
355,923
47,593,974
Python DataFrame particular columns conversion
<p>Current Data Frame output as below I need another Data Frame</p> <p><a href="https://i.stack.imgur.com/6ursh.png" rel="nofollow noreferrer">1</a></p> <p>import pandas as pd</p> <p>df = pd.DataFrame('c:\data\text.csv')</p> <p>print (df)</p> <p>My output is as below:</p> <pre><code> a b c ...
<p>This is what you can do :-</p> <p>Assuming the name of <code>DataFrame</code> is <code>df</code>, Convert each <code>dicts</code> of <code>df[c]</code> to <code>list</code>. Now you ned to unzip this list to add to the <code>DataFrame</code>. Unzip to get appropriate <code>list</code> and to add to <code>df</code>....
python|json|pandas|dataframe|pandas-datareader
0
355,924
47,691,228
How to fill missing date in timeSeries
<p>Here's what my data looks like: </p> <p><a href="https://i.stack.imgur.com/ktOQ3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ktOQ3.png" alt="my data looks like this"></a></p> <p>There are daily records, except for a gap from 2017-06-12 to 2017-06-16. </p> <pre class="lang-py prettyprint-ove...
<p>Here is a function I wrote that might be helpful to you. It looks for inconsistent jumps in time and fills them in. After using this function, try using a linear interpolation function (pandas has a good one) to fill in your null data values. Note: Numpy arrays are much faster to iterate over and manipulate than Pan...
python|pandas
0
355,925
47,814,449
Pandas apply function running slow
<p>I have this function that given an id, a number n and a dataframe returns the nth element on column "something" where the "id" is the id in the params.</p> <pre><code>def find_something(id,n,df): table = df.loc[(df['id'] == id)] try: something = df['something'].iloc[n-1] except: something = float(...
<p>I generated a similar dataset with 20 million rows and 60K IDs and ran it through your code; it took about an hour to finish. Generally, user-defined functions suffer from the lack of speed as <code>apply()</code> does not take advantage of Pandas’ vectorization. If executing <code>apply()</code> with large datasets...
python|pandas
1
355,926
47,867,359
Running Tensorflow graph multiple times over different input parameters: what kind of loop is efficient?
<p>For my particular problem, I need to re-run the once-constructed Tensorflow graph multiple times, each time re-initializing the variables to new values. Each execution of the graph is independent of the next. Think of it as setting up a model, and then training it 30 independent times with random initialisation per ...
<p>This is an interesting question, and I'm woking with ensembles of models myself. </p> <p>First of all, training models in a loop does so in series; neither Python loops or <code>tf.while_loop</code> will give you any parallelism across instances. That being said, (<code>tf.while_loop</code> combined with <code>tf...
performance|tensorflow|while-loop|parallel-processing|control-flow
1
355,927
47,686,115
Precision Matlab and Python (numpy)
<p>I'm converting a Matlab script to Python and I am getting different results in the 10**-4 order.</p> <p>In matlab:</p> <pre><code>f_mean=f_mean+nanmean(f); f = f - nanmean(f); f_t = gradient(f); f_tt = gradient(f_t); if n_loop==1 theta = atan2( sum(f.*f_tt), sum(f.^2) ); end theta = -2.2011167e+03 </code></...
<p>One possible source of the initial difference you describe (between means) could be numpy's <a href="https://github.com/numpy/numpy/pull/3685" rel="nofollow noreferrer">use</a> of <a href="https://en.wikipedia.org/wiki/Pairwise_summation" rel="nofollow noreferrer">pairwise summation</a> which on large arrays will ty...
python|matlab|numpy|precision
1
355,928
47,626,223
Str.Contains show only True values
<p>I am using str.contains on a large dataframe and I need a way such that str.contains returns the records where my str.contains function is True. (the dataframe is several thousand lines long and I am looking for 8 true responses).</p> <p>Thanks!</p> <pre><code>aa = filtered_to_df.body.str.contains('AA') aa.head(...
<p>important distinction: <code>str.contains</code> does not actually filter your dataframe or series, it just returns a boolean vector of the same dimension as the series you applied it on. </p> <p>e.g: if you have a series like this: </p> <pre><code>my_series = pd.Series(['hello world', 'hello', 'world']) print(my...
python|string|pandas|contain
2
355,929
49,304,433
Add a new index to a multi-indexed dataframe
<p>I have a 2 index (Date, Product) dataframe that looks like this:</p> <pre><code>[Date,Product] price D1 P1 1 P2 4 D2 P1 2 P2 2 D3 P1 2 P2 3 ... </code></pre> <p>How can I add a P3 lvl from date D2 so it looks like the below?</p> <pre><code>[Date,Prod...
<p>You can using <code>pd.concat</code></p> <pre><code>pd.concat([df,pd.DataFrame(data=[3,1],index=pd.MultiIndex.from_product([['D2','D3'],['P3']]),columns=['price'])]).sort_index() Out[68]: price Date Product D1 P1 1 P2 4 D2 P1 2 P2 2 P3...
pandas|dataframe|indexing|multi-index
1
355,930
49,182,199
Selecting df rows common with series
<pre><code>Datetime 2015-01-08 17:30:00 4942 2015-01-08 18:00:00 5983 2015-01-08 18:30:00 6732 Length: 3, dtype: int64 </code></pre> <p>I have next <code>df</code>:</p> <pre><code> A Datetime B 4166 Thu 2015-01-08 17:30:00 8 4942 Sat 2015-01-08 17...
<p>It is <code>isin</code></p> <pre><code>df=df.reset_index() s=s.reset_index() df.loc[df[['index','Datetime']].astype(str).sum(1).isin(s.astype(str).sum(1)),:] </code></pre>
python|pandas
1
355,931
49,308,887
Assign values to a dataframe by considering values in 2 columns of different dataframe as range
<p>The following code explains the scenario, I have a dataframe(df_ticker) with 3 columns</p> <pre><code>import pandas as pd df_ticker = pd.DataFrame({'Min_val': [22382.729,36919.205,46735.164,62247.61], 'Max_val': [36901.758,46716.06,62045.06,182727.05], 'Ticker':['$','$$','$$$','$$$$']}) df_ticker` </cod...
<p>One way is to define a custom mapping function and use <code>pd.Series.apply</code>.</p> <pre><code>def mapper(x, t): if x &lt; t['Min_val'].min(): index = 0 elif x &gt;= t['Max_val'].max(): index = -1 else: index = next((idx for idx, (i, j) in enumerate(zip(t['Min_val'], t['Max_...
python|python-2.7|pandas|numpy|dataframe
0
355,932
49,239,056
create dataframe by randomly sampling from multiple files
<p>I have a folder with several 20 million record tab delimited files in it. I would like to create a pandas dataframe where I randomly sample say 20 thousand records from each file, and then append them together in the dataframe. Does anyone know how to do that?</p>
<p>You could read in all the text files in a particular folder. Then you could make use of pandas <code>Dataframe.sample</code> (<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sample.html" rel="nofollow noreferrer">link to docs</a>). </p> <p>I've provided a fully reproducible example...
python-2.7|pandas
0
355,933
49,264,076
Normalize scipy sparse matrix with number of nonzero elements
<p>I want to divide each row of the csr_matrix by the number of non zero entries in that row.</p> <p>For example : Consider a csr_matrix A:</p> <pre><code>A = [[6, 0, 0, 4, 0], [3, 18, 0, 9, 0]] Result = [[3, 0, 0, 2, 0], [1, 6, 0, 3, 0]] </code></pre> <p>What's the shortest and efficient way to do it ?</p>
<p>Get the counts with <code>getnnz</code> method and then replicate and divide in-place into its flattened view obtained with <code>data</code> method -</p> <pre><code>s = A.getnnz(axis=1) A.data /= np.repeat(s, s) </code></pre> <p>Inspired by <a href="https://stackoverflow.com/a/49254531/"><code>Row Division in Sci...
python|numpy|scipy|sparse-matrix
6
355,934
48,992,794
datetime to decimal hour and minutes in python3
<p>I have a <code>dataframe</code> with <code>meteorological</code> data every <code>30 minutes</code>. With my datetime index I need to create a column with <code>timestamps</code>, but it must be in <code>decimal</code>. Here's the example below:</p> <pre><code>In [134]: df.index[0:3] Out[134]: DatetimeIndex(['2016...
<p>One way is to extract the hour and convert minutes to hours.</p> <p>There should be no need to convert to / from strings.</p> <pre><code>import pandas as pd idx = pd.DatetimeIndex(['2016-01-01 00:30:00', '2016-01-01 01:00:00', '2016-01-01 01:30:00'], ...
python|python-3.x|pandas|datetime|python-datetime
10
355,935
49,191,393
converting ddmmyy into mmyy format by using pandas?
<p>i have column(month) in the ddmmyy format, how i can convert that into mmyy format.</p> <p>Month<br> 6/1/2017 5/1/2017 i have used below code, can someone help</p> <pre><code>import pandas as pd df = pd.read_csv(r"C:\Users\venkagop\Subbu\UK_IYA.csv") df['Month']=pd.to_datetime(df['Month'],format='%d/%m/%y') df.to...
<p>I think you can convert column to datetimes in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow noreferrer"><code>read_csv</code></a> by parameter <code>parse_dates</code> and <code>dayfirst</code> and then convert to custom format by <a href="http://pandas.pydata.or...
pandas
1
355,936
49,247,971
Pandas: merge two dataframes with different index and missing values
<p>I am trying to merge two dataframe together. df2 has more sample points than df. I want to merge them base on the index of df in a way that for each timestamp for the closest non missing value to timestamp be the value.</p> <p>my original data set is categorical that is why I made the column as strings. </p> <pre...
<p>Use the <code>method='nearest'</code> parameter setting in your <code>reindex</code></p> <pre><code>df2.reindex(df.index, method='nearest') date 2018-03-12 20:44:02.753549 -1.6817565104 2018-03-13 20:44:02.753549 0.214975948416 2018-03-14 20:44:02.753549 nan 201...
python-3.x|pandas|indexing|pandas-groupby
2
355,937
49,338,649
Loading huge text files for neural machine translation with Pytorch
<p>In PyTorch, I have written a dataset loading class for loading 2 text files as source and targets, for neural machine translation purpose. Each file has 93577946 lines, and each of them allocates 8GB memory on Hard Disc.</p> <p>The class is as the following:</p> <pre><code>class LoadUniModal(Dataset): sources ...
<p>This shouldn't give you an error unless you load the entire data in memory at once. One suggestion I want to give you is: don't pad all sentences to a maximum length. In machine translation data, in general, sentence lengths vary a lot.</p> <p>Also, you can try smaller mini-batches of size <code>x</code> (ex., 32, ...
python|pytorch
1
355,938
49,077,428
Using sklearn for multiple linear regression
<p>I have a timeseries that looks like this:</p> <pre><code> date var1 var2 var3 var4 var5 var6 0 2004-09-30 6.252216 10.502101 4.965370 26.828754 3.321060 2.723686 1 2004-10-29 6.861840 9.776618 4.719399 27.621344 2.281346 4.449510 2 2004-11-30 8.171250 ...
<p>Instead of </p> <pre><code>df.var1.values.reshape(-1, 1) </code></pre> <p>Just pass</p> <pre><code>df.drop('date', axis=1) # .values should be optional here also </code></pre> <p>in its place.</p> <p>This gives you <code>df</code> with all columns excluding <code>date</code>.</p>
python|pandas|scikit-learn
1
355,939
49,099,163
Select pandas dataframe columns which have only one unique value
<p>How to effectively select pandas dataframe columns which have only 1 unique value?</p> <p>I'm aware of DataFrame and Series.nunique()</p>
<p>I think need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.nunique.html" rel="nofollow noreferrer"><code>DataFrame.nunique</code></a> for boolean mask and select by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow noreferrer"><c...
python|pandas|dataframe|unique
3
355,940
49,059,717
Pandas: how to drop rows that contain invalid month/day column combinations, such as February 30th?
<p>I have source data that uses 31 columns for day values, with a row for each month. I've melted the 31 day columns into a single day column, and now I want to combine the year, month, and day columns into a datetime(?) column so I can sort the rows by year/month/day.</p> <p>After the melt, my dataframe looks like so:...
<p>You can pass your df derictly to <code>to_datetime</code></p> <pre><code>pd.to_datetime(df,errors='coerce') Out[905]: # NaT # NaT # 1892-02-29 # NaT # NaT # NaT # 1896-02-29 # NaT # NaT dtype: datetime64[ns] df['New']=pd.to_datetime(df,errors='coer...
python|pandas
3
355,941
49,240,773
pandas: add missing timestamp into data frame with a default value
<p>I am using the following code to put data into a data frame:</p> <pre><code>import pandas as pd pd.set_option('display.float_format', lambda x: '%.3f' % x) df = pd.DataFrame(columns = ['time', 'value']) for x in data0.data: df = df.append({'time': x[0], 'value': x[1]}, ignore_index=True) df </code></pre> <p...
<p>you can set <code>time</code> as an index, reindex it so that you have all index values with 60 seconds interval and fill NaN's with <code>-1</code>:</p> <pre><code>In [242]: df.set_index('time').reindex(np.arange(df['time'].min(), df['time'].max(), 60)) \ .fillna(-1) \ .reset_index() Out[24...
python-2.7|pandas|timestamp|missing-data
0
355,942
49,211,095
Linear sum of shifted numpy arrays
<p>Given a (m,n) numpy array A, I would like to construct the (m-1,n-1) numpy array B such that B[i,j] equals </p> <pre><code>A[i+1,j+1]+A[i,j]-A[i+1,j]-A[i,j+1] </code></pre>
<pre><code>B = A[:-1, :-1] + A[1:, 1:] - A[1:, :-1] - A[:-1, 1:] </code></pre> <p>For example,</p> <pre><code>In [37]: A = np.arange(24).reshape((6,4)) In [38]: A Out[38]: array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22,...
arrays|numpy
5
355,943
48,999,145
Python Pandas Upsampling - Complex Issue Preserving Some np.Nans
<p>I have a dataframe that looks like this:</p> <pre><code> A B 2010-01-01 6.5 3.2 2010-02-01 7.2 np.Nan 2010-03-01 8.1 np.Nan 2010-04-01 4.3 5.6 2010-05-01 3.7 6.1 </code></pre> <p>I want to upsample to days and forward fill values. But in the case of <code>df...
<p>You can replace your <code>nan</code> to another value , waiting for <code>replace</code> back after we <code>resample</code> </p> <pre><code>df=df.fillna('replaceNAN') s=df.resample('D').ffill().replace('replaceNAN',np.nan) s.loc[s.isnull().any(1)] Out[456]: A B 2010-02-01 7.2 NaN 2010-02-02 7...
python|pandas|time-series|resampling
0
355,944
49,031,333
Finding order of conditions met in dataframe
<p>Say I have a set of data like so in a <code>pandas.DataFrame</code>:</p> <pre><code> A B C 1 0.96 1.2 0.75 2 0.94 1.3 0.72 3 0.92 1.15 0.68 4 0.90 1.0 0.73 ... </code></pre> <p>and I'd like to figure out the order in which the data meets conditions. If I were looking for A d...
<p>Here is one way to do that. This makes the assumption, which matches the context of your question, that we can describe the possible conditions as the previous value was less than or greater than the current value.</p> <h3>Code:</h3> <pre><code>def met_condition_at(test_df, tests): # for each column apply the...
python|pandas
0
355,945
49,200,745
Use re (regular expression) to parse only chunks of a line
<p>My laboratory is working with a software that generates a mess of data as output, so I’m trying to make things easier using Python. So far, I believe that the best approach is to generate lists and treat it as chunks of data, but that is not so easy: The first chunk of data is easy: the 3 columns are fixed and can b...
<p>You don't need regex for this problem. You can do something like this:</p> <pre><code>text = """s 27 1.00 STRE 30 16 OC 1.355049 f1291 50 s 34 -1.00 BEND 1 3 7 CCC 119.62 f1037 26 f485 10 s 89 1.00 TORS 31 30 16 19 COCC 0.24 f161 14 f104 46 f87 19 f43 10 s 91...
python|python-3.x|pandas|dataframe
2
355,946
49,301,242
How to write Unicode object in excel
<p>I'm writing a data frame in excel using group by function. I get an error <code>AttributeError: 'Unicode' object has no attribute 'to_excel'</code>.</p> <p>DataFrame: </p> <pre><code>final_day_wise = daily_sales_data.loc [ : , ["Placement# Name", "Date", "Delivered Impressions", "Clicks", "CTR", "...
<p>When you do <code>groupby</code> on final_day_wise, you are getting a dictionary like object where the key is an item from the column that you grouped on (in your case 'Placement# name') and your value is a groupby object. You are getting an error when you try <code>placement.to_excel()</code> because placement is a...
python|pandas|pandas-groupby
0
355,947
48,980,725
Using regular expression in pandas to select before a certain divider \r\
<p>Hi I'm trying to without succeed to use regular expression to select he string before the \r\ , ideally in majority of the times is a word follow by a coma. But as showed the \r\ and some other obstacles appear .Example below:</p> <pre><code> var Sao Paulo , Brazil \r\n Details Description .... Rio de Janeiro , ...
<p>You can use either</p> <pre><code>df["var"].str.extract("(.*)\\\\r") </code></pre> <p>or </p> <pre><code>df["var"].str.extract(r"(.*)\\r") </code></pre> <p>Notice the <code>r</code> before quotation mark. You can read more at <a href="https://stackoverflow.com/questions/2241600/python-regex-r-prefix">Python rege...
python|regex|pandas
0
355,948
49,301,203
keras error got an unexpected keyword argument 'epochs'
<p>I'm trying to train a network in Keras to classify an image and after debugging the last issue got this one of unexpected keywork epochs</p> <pre><code>muiruri_samuel@training-2:~/google-landmark-recognition-challenge$ python train.py Using TensorFlow backend. Found 981214 images belonging to 14951 classes. Found 2...
<p><code>model.compile</code> does not take an epochs parameter. Only <code>fit</code> and <code>fit_generator</code> do.</p>
python|tensorflow|keras
2
355,949
49,255,775
How to append data from a certain column to one cell?
<p>I have the following data set. Only the data in the "internalnotes" needs to be in one cell. All the other data is the same for a CaseNumber, except the "internalnotes". The CaseNumber column is not the index for my data. </p> <p>How can I append all the data in the "internalnotes" for a specific CaseNumber in one ...
<p>This is one way. <code>groupby.apply(list)</code> will aggregate all the <code>internalnotes</code> per group into a list.</p> <pre><code>group_cols = ['CaseNumber', 'ProcessInstanceDescription', 'ProdOpsCaseOwner', 'personname', 'SNLAnalystEntryDesc'] ans_new = ans_new.groupby(group_cols)['internaln...
python|string|pandas|dataframe
0
355,950
49,308,530
Missing values in Time Series in python
<p>I have a time series dataframe, the dataframe is quite big and contain some missing values in the 2 columns('Humidity' and 'Pressure'). I would like to impute this missing values in a clever way, for example using the value of the nearest neighbor or the average of the previous and following timestamp.Is there an ea...
<p>Consider <code>interpolate</code> (<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.interpolate.html" rel="noreferrer">Series</a> - <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.interpolate.html" rel="noreferrer">DataFrame</a>). This example sho...
python|pandas|nan|imputation
29
355,951
49,159,725
Transform rows with common key to single row with multiple columns
<p>I have two dataframes to merge into one. The <code>main_id</code> frame contains lists of unique ids. The <code>ref_data</code> frame contains some data about the objects in <code>main_id</code>. Some of the ids are referenced twice, some only once, so I think I need a one-to-many join. I want to capture both the <c...
<p>This should work for you, just use <code>groupby</code> no need to merge</p> <pre><code>mrg = ref_data.groupby('main_id').apply(lambda x: x[['period','quantity']].values.ravel()) pd.DataFrame(mrg.tolist(),index=mrg.index,columns=['period_1_ref','period_1_val','period_2_ref','period_2_val']) period_1_ref p...
python|pandas
1
355,952
49,053,885
Calculating rational basis for the nullspace using numpy
<p>I am trying to calculate the rational basis for null space of a matrix. There is quite a few posts about how nullspace is calculated using Python/numpy but they calculate it for orthonormal basis and not for the rational basis. Here is how this is done in MATLAB:</p> <p><code>ns = null(A,'r')</code></p> <p>When I ...
<p><a href="http://docs.sympy.org/latest/tutorial/matrices.html" rel="nofollow noreferrer">SymPy</a> does that out of the box, although (being symbolic, and in Python) not as fast as NumPy or Scipy would. An example with floating point input:</p> <pre><code>from sympy import Matrix, S, nsimplify M = Matrix([[2.75, -1....
python|matlab|numpy|linear-algebra
2
355,953
49,203,568
loop for loading files and assigning variables
<p>I am brand new to python and am working on a school project. I was able to write the code to make my project work. However, I realize the way I did it is terribly inefficient and that there is probably a better way to store and work with the data in a 3D numpy array. I want to learn a better way to write code like t...
<p>You can just loop through the files you stored in your list, and append everything to one big numpy array. On that numpy array your can do your masking...</p> <pre><code>#path to directory containing hdf files file_path = '/Data/2018_2001_georef_MODIS/' #Get a list of all the .hdf files in the directory MODIS_file...
python|loops|numpy|for-loop
0
355,954
48,995,577
Training in tensor flow cpu version too slow
<p>I have installed Tensorflow cpu version.I have only few images as dataset and I am training on a machine with 4GB ram and Core i5 3340m 2.70GHZ with batch size 1 and it is still extremely slow.the size of all images is same (200X185 i think).Will it train like this ? kindly tell me how can I speed up this process?</...
<p>If your network is deep, it could take a long time to train your network using CPU as it is not optimized like GPU for calculations.</p> <p>I would suggest you to get a graphic card, even a old version of graphic card can significantly improve the performance (it could be like 100x faster).</p>
python|python-3.x|tensorflow|machine-learning|training-data
1
355,955
48,895,397
Vectorized component wise multiplication
<p>Store 2N vectors of size d in two matrices <code>a</code> and <code>b</code> where <code>a.shape = b.shape = (N,d)</code> (so <code>a[i]</code> is the ith vector in <code>a</code>, which contains N vector, same with <code>b</code>).</p> <p>I would like to construct in a vectorized manner the tensor <code>T</code> o...
<p>With <code>einsum</code> the calculation writes itself: </p> <pre><code>np.einsum('ip,iq-&gt;ipq', a,b) </code></pre> <p>That expression also makes it clear that there's no summation - just products. This is a kind of outer product, not an inner or matrix one. In which case <code>tensordot</code> won't help. But...
python|numpy
2
355,956
49,002,272
setting nan to entire axis if any nan exists in axis in numpy
<p>I have a 3 dimensional numpy array with shape <code>(x,y,R)</code>. For each <code>(x,y)</code> pair, I have a 1D numpy array of R values. I want to set the entire array to <code>nan</code> if any of the R values are <code>nan</code> or <code>zero</code>. I tried something like</p> <pre><code># 3d np array is calle...
<p><code>nan</code> has the peculiar property of comparing not equal to anything, <em>including</em> <code>nan</code> itself:</p> <pre><code>&gt;&gt;&gt; y = np.random.random(size=(2,2,3)) &gt;&gt;&gt; y[0,0,2] = np.nan &gt;&gt;&gt; y[0,1,0] = np.nan &gt;&gt;&gt; y[0,0,1] = np.nan &gt;&gt;&gt; y[0,1,2] = np.nan &gt;&g...
python|numpy
5
355,957
48,998,897
Removing decimal seconds from time format data in DataFrame
<p>I've got two large df's from two xlsx spreadsheets and would like to merge them 'on' time stamp ['Time'] data. </p> <p>The problem is that one data set has recorded time to decimal seconds and the other to whole seconds. This means that the two data set ['Time'] keys never match up... </p> <pre><code>df1 Time ...
<p>In <code>df1</code>, you can just set microseconds to 0:</p> <pre><code>df1['Time'] = pd.to_datetime(df1['Time']).apply(lambda x: x.replace(microsecond=0)) </code></pre> <p>Then perform your merge as normal.</p>
python|pandas|time
5
355,958
48,911,071
More effective way to use pandas get_loc?
<p><strong>Task:</strong> Search a multi column dataframe for a value (all values are unique) and return the index of that row. </p> <p><strong>Currently:</strong> using get_loc, but it only seems allow a pass of a single column at a time, resulting in quite a ineffective set of try except statements. Although it work...
<p>Consider this example instead using <code>np.random.seed</code></p> <pre><code>np.random.seed([3, 1415]) df = pd.DataFrame( np.random.randint(200 ,size=(4, 4)), columns=list('ABCD')) df A B C D 0 11 98 123 90 1 143 126 55 141 2 139 141 154 115 3 63 104 128 120 </code></p...
python|pandas|indexing
7
355,959
48,971,488
Python2.7: FIlter out group from dataframe based on condition in groupby
<p>I have a dataframe and I would like to filter the dataframe further to only include a group whose rows do not have a certain value in a column </p> <p>For eg, in the dataframe, since hamilton has an overtake in lap3 of his stint 1, I want to remove ALL of hamilton's stint 1 laptime records from the dataframe below....
<p>I believe you need get all groups by filtering and then filter again by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="nofollow noreferrer"><code>isin</code></a>:</p> <p>Notice: Thank you, @Vivek Kalyanarangan for improvement by <a href="http://pandas.pydata.org/pandas-...
python|pandas|dataframe
1
355,960
49,205,354
DataFrame Split On Rows and apply on header one column using Python Pandas
<p>I'm working on some project and came up with the messy situation across where I've to split the data frame based on the first column of a data frame, So the situation is here the data frame I've with me is coming from SQL queries and I'm doing so much manipulation on that. So that is why not posting the code here. ...
<p>I think you can do this:</p> <pre><code>df = df.set_index('Placement# Name') df['Date'] = df['Date'].dt.strftime('%M-%d-%Y') df_sub = df[['Delivered Impressions','Clicks','Conversion','Spend']].sum(level=0)\ .assign(Date='Subtotal') df_sub['CTR'] = df_sub['Clicks'] / df_sub['Delivered Impressions'] df_sub['eCPA...
python|python-2.7|pandas|loops|xlsxwriter
1
355,961
48,996,822
Python - Drop rows from a Pandas DataFrame that contain numbers
<p>I have a dataframe with one column like this:</p> <pre><code>Value xyz123 123 abc def </code></pre> <p>I want to remove any rows that contain numbers so I end up with a dataframe like this:</p> <pre><code>Value abc def </code></pre> <p>I have tried</p> <pre><code>df = df[df['Value'].str.contains(r'[^a-z]')] </c...
<p>Independent from what looks like an issue with variable naming, you could be more explicit about removing only rows with numbers:</p> <pre><code>df[~df.Value.str.contains(r'\d')] Value 2 abc 3 def </code></pre> <p><code>\d</code>:</p> <blockquote> <p>Matches any Unicode decimal digit (that is, any charac...
python|pandas|data-analysis
4
355,962
49,214,570
What do the args and kwargs do in pandas.DataFrame.clip?
<p>I've been working on the documentation for <code>pandas.DataFrame.clip</code>. I need to document what the <code>*args</code> and <code>**kwargs</code> do for that function.</p> <p><a href="https://github.com/Dpananos/pandas/blob/docstring_clip/pandas/core/generic.py#L5599" rel="nofollow noreferrer">Here</a> is a ...
<p>They seem to be used for compatibility with numpy libraries [1] in this file <a href="https://github.com/pandas-dev/pandas/blob/fb556ed64cd0e905e31fe39723a8a4bca9cb112d/pandas/compat/numpy/function.py#L137" rel="nofollow noreferrer">here</a>.</p> <p>In the original file, args, kwargs are being passed into <a href="...
python|pandas
2
355,963
49,074,021
Repeat Rows in Data Frame n Times
<p>consider a data frame defined like so:</p> <pre><code>import pandas as pd test = pd.DataFrame({ 'id' : ['a', 'b', 'c', 'd'], 'times' : [2, 3, 1, 5] }) </code></pre> <p>Is it possible to create a new data frame from this in which each row is repeated <code>times</code> times, such that the result looks like t...
<p>Use a combination of <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="noreferrer"><strong><code>pd.DataFrame.loc</code></strong></a> and <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.repeat.html" rel="noreferrer"><strong><code>pd.Index.rep...
python|pandas
94
355,964
49,085,456
Most efficient way to stretch an image in Python NumPy
<p>I want a function to take in an image as a numpy array and remap the values to a new range (0, 1) based on a specified maximum and minimum value from the input range. I've got a working function, but I'm iterating through the array and it takes about 10 seconds to complete. Is there a more efficient way to perform...
<h2>Bug #1</h2> <p>You have a bug in your code.</p> <p><code>image[i] = 1. or 0.</code> always evaluates to <code>1.0</code> because <code>1.</code> acts <a href="https://stackoverflow.com/a/39984051/1953800">truthy</a>.</p> <p>Instead that block should look like:</p> <pre><code>if image[i] &lt; minimum: image[...
python|python-3.x|numpy|scipy
2
355,965
49,172,608
Write numpy array to binary file efficiently
<p>I need an efficient solution for writing a large amount of data to a binary file. Currently I use the numpy method <code>.tofile</code>, which consumes most of the runtime. My MWE:</p> <pre><code>import numpy as np def writeCFloat(f, ndarray): np.asarray(ndarray, dtype=np.float32).tofile(f) def writeCInt(f, nd...
<p>You can use <code>dask</code> to run this operation in parallel. This also allows you to scale beyond the memory limits of a single thread.</p> <p>Depending on your use case and the filetype you want the data to end up in, you could do the following:</p> <p><strong>MCVE</strong></p> <pre class="lang-py prettyprint-o...
python|pandas|numpy|binary|dask
0
355,966
49,139,665
Python: Pandas Dataframe Column Headers Look Strange After Groupby
<p>I implemented the following groupby statement in my code. The purpose of the code below is to provide the minimum date from the "DTIN" column by unique EVENTID. </p> <pre><code>df_EVENT5_future_2 = df_EVENT5_future.groupby('EVENTID').agg({'DTIN': [np.min]}) df_EVENT5_future_3 = df_EVENT5_future_2.reset_index() </...
<p>This is as per @Wen's suggestion. You don't need to use <code>agg</code> for this. Simply use <code>groupby.min()</code> and set <code>as_index=False</code>:</p> <pre><code>result = df.groupby('EVENTID', as_index=False)['DTIN'].min() </code></pre> <p>Please do not upvote or accept this answer, as this is a duplica...
python|pandas|indexing|pandas-groupby
0
355,967
58,900,954
Error while adding error bars to subplots in seaborn
<p>I have the following example code which I want to plot as bar subplots using seaborn in one figure. I can plot the actual data as bar plots but when i try to add error bars, i get the following error:</p> <pre><code>AttributeError: 'NoneType' object has no attribute 'seq' </code></pre> <p>code is:</p> <pre><code>...
<p>Maybe you mean something like this:</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt df1 = pd.DataFrame({ 'A': ['7.5'], 'B': ['2.4'] }).astype(float) df1_err = pd.DataFrame({ 'A': ['2.3'], 'B': ['1.2'] }).astype(float) fig, axes = plt.subplots(nrows=1, ncols=2...
pandas|matplotlib|seaborn|python-3.5
1
355,968
58,648,875
How to retain all columns in pandas while using regex
<p>There are around more than 100 columns with first two columns as primary keys.</p> <p>As per screenshot, Col A and B are primary keys and we need to find out all the columns having "cad" in their names and then convert those column into "usd" by multiplying them 0.75. Also, the column names should be renamed from "...
<pre><code>cad_cols = df.filter(regex='cad').columns df[cad_cols] *= 0.75 df.columns= [c.replace('cad','usd') for c in df.columns] </code></pre>
regex|pandas
0
355,969
58,811,799
How to get the moving window average after grouping by multiple columns
<p>First, I want to grouby by the columns, <code>name</code>, <code>group</code> and <code>place</code>. Then, I want to get the average value <code>y</code> of adjacent two months. Last, I want to add the average value to the origin dataframe.</p> <p><code>The origin dataframe:</code></p> <pre><code>import pandas a...
<p>The 4th level of index is your original index </p> <pre><code>df['new']=temp.reset_index(level=[0,1,2], drop=True) </code></pre>
python|pandas|pandas-groupby
1
355,970
58,847,519
Pandas Groupby to get average of each group
<p>Suppose I have a df -</p> <pre><code>Player Challenge Description James ABC Desc1 Bob ABC Desc1 Bob XYZ Desc X Bob ABX101 Desc4 Alex XYZ Desc X Mark ABC123 Desc...
<p>Use:</p> <pre><code>count_challenge=df.groupby('Player').Challenge.count() print(count_challenge) Player Alex 2 Bob 4 James 1 Jessica 1 Lynn 2 Mark 5 Name: Challenge, dtype: int64 </code></pre> <p>If you don't want count duplicates:</p> <pre><code>count_challenge=df.drop_duplicat...
python-3.x|pandas|dataframe|pandas-groupby
2
355,971
58,834,104
Concatenate values in ascending order using pandas
<p>I have a DataFrame with some columns. The columns are: A1, A2, A3. I would like to create a new column let's name it 'CON'. The new column is a string concatenated from A1, A2, A3 with a separator. The concatenation is sorted by the values of the values of the columns.</p> <p>For example:</p> <pre><code>data = pd....
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>DataFrame.apply</code></a> with <code>join</code> and sorted:</p> <pre><code>data['CON'] = data.apply(lambda x: '-'.join(sorted(x)), axis=1) </code></pre> <p>Alternative with list com...
python|pandas|sorting|concatenation
3
355,972
59,023,634
How do you combine like column names into separate rows in Pandas
<p>If I have the following data, and read it in, I get column names with .1 or .2 for like columns. Here is the data:</p> <pre><code>import io dfff=io.StringIO("""address,phone,name,website,type,address,phone,name,website,type,address,phone,name,type 123 APPLE STREET,555-5555,APPLE STORE,APPLE.COM,BUSINESS,456 peach ...
<p>You can use wide_to_long.</p> <pre><code>df.columns = [f'{x}.0' if '.' not in x else x for x in df.columns] df['id'] = df.index df = pd.wide_to_long(df, stubnames=['address', 'phone', 'name', 'website', 'type'], i='id', j='row', sep='.') df.reset_index(drop=True) Out[1]: address phone n...
python|pandas
1
355,973
58,736,007
Get Column with Max Index Across a Group in Pandas Dataframe
<p>I have the following Data in a Pandas DataFrame</p> <pre><code>import pandas as pd data = [['AAA','2019-01-01', 10], ['AAA','2019-01-02', 21], ['AAA','2019-02-01', 30], ['AAA','2019-02-02', 45], ['BBB','2019-01-01', 50], ['BBB','2019-01-02', 60], ['BBB','2019-02-01', 70],['BBB','2019-02-02'...
<p>You can groupby and transform for idxmax, eg:</p> <pre><code>dfx['MAXIDX'] = dfx.groupby('NAME').transform('idxmax') </code></pre>
python-3.x|pandas|pandas-groupby
4
355,974
58,775,848
TFLIte Cannot set tensor: Dimension mismatch on model conversion
<p>I've a keras model constructed as follows</p> <pre class="lang-py prettyprint-override"><code>module_url = "https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4" backbone = hub.KerasLayer(module_url) backbone.build([None, 224, 224, 3]) model = tf.keras.Sequential([backbone, tf.keras.layers.Dense(len(c...
<p>Had the same problem when using</p> <pre class="lang-py prettyprint-override"><code>def representative_dataset_gen(): for _ in range(num_calibration_steps): # Get sample input data as a numpy array in a method of your choosing. yield [input] </code></pre> <p>from <a href="https://www.tensorflow...
python|tensorflow|keras|iot|tensorflow-lite
3
355,975
58,850,367
How to read a CSV file that contains no headers using Pandas, capture data in the first column only and perform deletion?
<p>I have a CSV file that contains information about people and all sorts of data that takes up more than 100 columns. There are no headers and my main <strong>intention is to grab the peoples' names only</strong>. Not the other data related to it. How can I do this?</p> <p>This is my CSV file --- 'data.csv':</p> <pr...
<p>Add parameter <code>header=None</code> to <code>read_csv</code> for default columns <code>0,1,2</code>...:</p> <pre><code>df = pd.read_csv(csv_filename, header=None) names = ['Timothy', 'Joshua', 'Rio', 'Catherine', 'Poorva', 'Gome', 'Lachlan', 'John', 'Lio'] </code></pre> <p>Then select first column by <code>df...
python|pandas|csv
1
355,976
58,636,416
Merge and fill missing values based on multiple columns from another dataframe in Python
<p>In order to merge two dataframes based on <code>year</code> and <code>city</code>, I want to fill missing values in <strong>df1</strong> <code>gdp_value</code> and <code>growth_rate</code> from the values in <code>gdp</code> and <code>rate</code> respectively from <strong>df2</strong>.</p> <p><strong>df1</strong></...
<p>As mentioned in the question you can also use update depending on your data and needs:</p> <pre><code>df1 = df1.set_index(['year', 'city']) df1.update( df2 .set_index(['year', 'city'])\ .rename(columns={'gdp':'gdp_value','rate':'growth_rate'})\ ) df1 = df1.reset_index() </code></pre> <hr> <p>One way i...
python|pandas|dataframe
2
355,977
58,637,314
pandas rolling mean in the future purely by date
<p>I would like to get the average, and max for a certain time in the future of each row. My dataframe has a <code>datetime</code> and a <code>cost</code> column. </p> <p>Here's how I'm getting the past:</p> <pre><code>df.rolling('5d', on='datetime')['cost'].mean() </code></pre> <p>Works great, but I need to do the ...
<p>I just reversed the time and then I'll use that to get the future.</p> <p>this is as yet untested, but I'll try it out tomorrow:</p> <pre><code>rows = df.shape[0] - 1 reverse_time = [] last_date = '' for ix in df.index: if ix == 0: last_date = df['datetime'][rows] reverse_time.append(last_date)...
python|pandas|datetime
0
355,978
59,033,562
How to merge dataframe and date_range Series?
<p>I have a dataframe with user transactions:</p> <pre><code>date amount 2019-11-25 100 2019-11-25 40 2019-11-23 44 2019-10-30 1000 </code></pre> <p>Date column has gaps. This makes time-serier plottng a bit weird. In order to fill the gaps I've created Series:</p> <pre><code>allthosedays = pd.DataFrame({ ...
<blockquote> <p>This makes time-serier plottng a bit weird.</p> </blockquote> <p>I think one reason is duplicated <code>DatetimeIndex</code> value(s) <code>2019-11-25</code>, so it should be problem.</p> <p>One possible solution is use <code>sum</code> per datetimes for unique values with aggregation, e.g. <code>su...
python|pandas
1
355,979
58,630,031
How to add Country code(+852) before the phone number in a dataframe
<p>I have a CSV file and there is a column (Phone). However, there is no country code before the phone number. What is the syntax I should use in order to add <code>+852</code> into every value under the "Phone" column?</p> <p>Also, how could I remove the space within the phone number for every value under "Phone" col...
<p>Assuming your 'phone' column is in string format you could do the following commands:</p> <p>a) use replace to remove the spaces (where df is the name of your datraframe)</p> <pre><code>df.phone = df.phone.apply(lambda x: x.replace(" ", "")) </code></pre> <p>b) concatenate the phone column with the country code</...
python|python-3.x|pandas|numpy|dataframe
1
355,980
58,643,896
How to fix "model.predict is not a function" (tensorflow.js)?
<p>I wanted to test lack of errors code bellow:</p> <pre><code>'use strict' const tf = require('@tensorflow/tfjs'); require('@tensorflow/tfjs-node'); const { createCanvas, createImageData } = require('canvas'); const canvas = createCanvas(800, 600); async function load_model() { let m = await tf.loadLayersModel...
<p><code>predict</code> is on the promise returned by then</p> <pre><code>model.then(function (res) { const example = tf.browser.fromPixels(canvas); const prediction = res.predict(example); console.log(prediction); }, function (err) { console.log(err); }); </code></pre>
javascript|tensorflow.js
5
355,981
58,850,428
Iterating over all batches of a generator in keras
<p>I have a dataset formed by images and labels, loaded with a generator such as:</p> <pre><code>generator = image_generator.flow_from_directory(batch_size=BATCH_SIZE, directory=val_dir, shuffle=False,...
<p>As mentioned in the <a href="https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image/ImageDataGenerator" rel="nofollow noreferrer">official link</a>:</p> <pre class="lang-py prettyprint-override"><code>for e in range(epochs): print('Epoch', e) batches = 0 for x_batch, y_batch in datagen.f...
tensorflow|keras|conv-neural-network
1
355,982
58,996,451
Adapting Pytorch "NLP from Scratch" for bidirectional GRU
<p>I have taken the code from the tutorial and attempted to modify it to include bi-directionality and any arbitrary numbers of layers for GRU.</p> <p>Link to the tutorial which uses uni-directional, single layer GRU: <strong><a href="https://pytorch.org/tutorials/intermediate/seq2seq_translation_tutorial.html" rel="n...
<p>So I'm not sure if this is 100% correct as I'm just learning how to program RNNs, but i changed my code in a couple of extra areas.</p> <p>For one you'll notice that the error says m1: <code>[1x384]</code> so the result of</p> <p><code>torch.cat((embedded[0], hidden[0]), 1))</code></p> <p>when putting this throug...
python|deep-learning|nlp|pytorch|recurrent-neural-network
1
355,983
58,899,770
Detect available time periods in dataframe
<p>I work with varying datasets (panel data) and need to detect programmatically if I have daily, monthly, quarterly or only yearly data available. All the datasets have a date column with datetime format (e.g. yearly data only has year-end dates 31-12-2017, 31-12-2018 etc.; daily data might look like 02-02-2018, 03-05...
<p>To check whether your DataFrame contains e.g. daily data (according to your criterion), you can take the following approach:</p> <p>As a source DataFrame I took:</p> <pre><code> Value Date 2019-01-10 20 2019-01-15 12 2019-01-22 10 2019-02-08 11 2019-02-22 13 2019-03-11 ...
python|pandas|datetime
1
355,984
58,848,111
Calculate binary entropy loss using a function in pytorch
<p>I have a problem about calculating binary cross entropy. The way I know that works out in pytorch is:</p> <pre><code>import torch import torch.nn as nn import torch.nn.functional as F def lossfunc(): return F.binary_cross_entropy criterion = lossFunc() input = torch.randn((3, 2), requires_grad=True) target = t...
<p>I think you're confusing the <code>nn</code> api with the functional <code>F</code> api. In functional api, loss function <code>F.binary_cross_entropy</code> can be used as a function directly.</p> <p>In <code>nn</code> api, you need to create an object of the loss class such as <code>criterion = nn.BCELoss()</code...
python|deep-learning|pytorch
1
355,985
58,851,553
Indexing into array columns of a pandas DataFrame
<p>I have a pandas DataFrame that contains some array columns. What is the recommended way to index some of these columns by different position indices? For example, from the array column named <code>l</code> I need the second elements, from the array column named <code>a</code> I need the first elements. The results s...
<p>I think it depends.</p> <p>First solution is most general, working always if indices not exist - then returned <code>NaN</code>s. But it is also reason for slowiest solution if large <code>DataFrame</code>.</p> <pre><code>print (df['l'].str[3].to_frame('l').join(df['a'].str[2])) l a 0 NaN baz 1 10.0 ...
python|pandas|dataframe|indexing
1
355,986
59,016,463
how to import excel files from two folders in python
<p>I initially have a code that is working in merging files in one folder. However, the work expanded to merge files in two folders. I edited the code to add first the list of files in two folders. That part is working but will not work in the actual for loop part. I am thinking this could be because of the current wor...
<p>I suggest you change your code design a little bit. Make a list of all the folders and iterate on them and load the files in the loop. You can use this code for as many folders as you want</p> <pre><code>import os from pathlib import Path def merge_files_in_folder(folder): df = pd.DataFrame() for excel_fi...
python|pandas
2
355,987
58,978,772
How can I use Python to walk through files in directories and output a pandas data frame given certain constraints?
<p>So I'm using Pyhton, and I have a parent directory, with two child directories, in turn containing many directories, each with three files. I want to take the third file (which is a .CSV file) of each of these directories, and parse them together into a pandas dataframe. This is the code I have this far</p> <pre><c...
<p>IIUC we can do this much easier using a recursive function from pathlib :</p> <pre><code> from pathlib import Path csv = [f for f in Path(r'parent_dir').rglob('*C74*.csv')] df = pd.concat([pd.read_csv(f) for f in csv]) </code></pre> <p>if you want to subset your list again you could do </p> <pre><code>...
python|pandas|os.walk
1
355,988
58,786,180
Apply custom rolling function to pandas dataframe with datetime index
<p>I have a pandas dataframe on which I wish to apply my own custom rolling function as follows:</p> <pre><code>def testms(x, field): mu = np.sum(x[field]) si = np.sum(x[field])/len(x[field]) x['mu'] = mu x['si'] = si return x df2 = pd.concat([pd.DataFrame({'A':[1,1,1,1,1,2,2,2,2,2]}), pd.Da...
<p>If use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.window.Rolling.apply.html" rel="nofollow noreferrer"><code>Rolling.apply</code></a> it working differently like <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.apply.html" rel="nofollo...
python|pandas|rolling-computation
1
355,989
58,950,697
Pandas read_csv end reading at first linebreak
<p>I am trying to read a csv file with some garbage at the top, but also garbage at the bottom of the interesting data. I need to read multiple files and the length of the interesting data varies. Is there a way to let the <code>pd.read_csv</code> command know that the dataframe ends at the first linebreak?</p> <p>Exa...
<p>Two ways you could implement this </p> <p>1) use skipfooter parameter of read csv , it tells the function the Number of lines at bottom of file to skip</p> <pre><code>pd.read_csv("in.csv",skiprows=45,skipfooter=2) </code></pre> <p>2) Read the file as it is and later use dropna function, this should drop the Garba...
python|pandas
1
355,990
58,921,117
fetching most recent values in pandas dataframe
<p>Here is a sample of my pandas dataframe</p> <pre><code>Player_A Player_B Gain_A Gain_B John Max -3 3 Max Lucy 4 -4 Lucy John 1 -1 Max John -5 5 John Lucy -2 2 </code></pre> <p>I wish to cr...
<p>IIUC, you can convert the data to long form, rolling sum on groupby:</p> <pre><code>new_df = (pd.wide_to_long(df.reset_index(), stubnames=['Player','Gain'], i='index',j='type', sep='_', suffix = '.*' ) .sort_index() ) new_df['Sum_2'] = (new_df.gr...
python|pandas
0
355,991
58,664,561
Replace phrases in string that aren't all letters Pandas
<p>I have a pandas series</p> <pre><code>pd.Series({'products':['deskjet 2620 all in one wireless inkjet printer', 'z3700 wireless optical mouse white' ]}) </code></pre> <p>I want to replace all the words that aren't alphabetic from beginning to end. I want the output</p> <pre><code>pd.Series({'products':['deskjet a...
<pre class="lang-py prettyprint-override"><code> # function to check if number or character def replace_nums(x): no_digits="" for i in x: if not i.isdigit(): no_digits+=i return no_digits # eg series exdict = {'Geeks' : '10abc', 'for' : '204f5', 'geeks' : '30rew'} ...
pandas
0
355,992
58,671,517
Is there a faster way to achieve the same result?
<p>I have this python code:</p> <pre><code> for i, num in enumerate(num_arr): if num &gt; threshold: num_arr[i] = threshold </code></pre> <p>'num_arr' is a simple array filled with integers, 'threshold' may vary from 10 to 100,000. Is there any faster way to achieve the same result? bitwise ope...
<p>You can use <a href="https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.ndarray.clip.html" rel="nofollow noreferrer"><strong><code>.clip(..)</code></strong> [numpy-doc]</a> for that. For example:</p> <pre><code>num_arr = num_arr<b>.clip(max=threshold)</b></code></pre> <p>For example:</p> <pre><code...
python|numpy|processing-efficiency
1
355,993
58,639,696
tensorflow session stops when try to print values
<p>I have a problem with tesorflow session or python. Everytime I try to print some tensor values to check the network works well, the program stops with this error.</p> <blockquote> <p>" Process finished with exit code -1073741819 (0xC0000005) "</p> </blockquote> <p>I use <code>python 3.5</code> and <code>tensorfl...
<p>I solved the problem by making a new pycharm project.</p> <p>And the error about GPU, "GPU libraries are statically linked, skip dlopen check."</p> <p>→ I downgraded the tensorflow-gpu version to 1.13.1 because 1.14.0 may not compatiable with CUDA 10.0. </p>
python|tensorflow|session
0
355,994
59,036,708
Pandas: Why is Series indexing using .loc taking 100x longer on the first run when timing it?
<p>I'm slicing a quite big pandas series (~5M) using .loc and I stumble upon some weird behavior when checking times in an attempt to optimize my code. </p> <p>It's weird that the first slicing attempt like <code>series_object.loc[some_indexes]</code> is taking 100x longer than the following ones.</p> <p>When I try <...
<p>This code is likely not idempotent (has side effects that impact its execution).</p> <p><code>timeit</code> will run the code once first to measure the time and deduce the number of loops and runs it should use. If your code is not idempotent (has side effects, like cashing) then that first run (not recorded) will ...
python|pandas|indexing|time|timeit
0
355,995
59,019,504
numpy count occurrences from external set
<p>I want to count the number each element from a set appears in an ndarray. Ex: </p> <pre><code>set = {1, 2, 3} a = np.array([1, 1, 3, 1, 3]) res = {1:3, 2:0, 3:2} </code></pre> <p>Seems like <code>np.unique</code> has no option for providing "base" set of elements. What's the fastest way of doing it?</p>
<p>Here's one way with <code>np.unique</code> and <code>np.searchsorted</code> -</p> <pre><code>u,c = np.unique(a,return_counts=True) s = np.array(list(set)) idx = np.searchsorted(u,s) idx[idx==len(u)] = 0 # account for set elements out-of-bounds in a mask = u[idx]==s cm = c[idx]*mask out = dict(zip(s,cm)) </code></pr...
python|numpy
2
355,996
58,710,689
Modify a specific column of a specific row in a CSV file in Python
<p>I have a CSV file that contains a translation of different labels. Now I want to edit or add a certain value in the ElementsButtonDelete row of a specific column. </p> <pre><code>name en_GB de_DE ElementsButtonAbort Abort Abbrechen ElementsButtonConfirm Confirm Bestätigen ElementsButton...
<p>use append</p> <pre><code>df = df.append({'Name' : 'value' , 'en_GB' : 'value'} , ignore_index=True) </code></pre>
python-3.x|pandas|csv
0
355,997
58,841,355
BodyPix: Real-time Person Segmentation
<p><a href="https://github.com/tensorflow/tfjs-models/tree/master/body-pix" rel="noreferrer">BodyPix</a> is an open-source machine learning model which allows for person and body-part segmentation in the browser with TensorFlow.js. I will like to convert the model to a .pb frozen graph in order to use it on Python.</p...
<ul> <li>Download the model.json file</li> </ul> <p>Eg: <a href="https://storage.googleapis.com/tfjs-models/savedmodel/bodypix/resnet50/float/model-stride16.json" rel="noreferrer">https://storage.googleapis.com/tfjs-models/savedmodel/bodypix/resnet50/float/model-stride16.json</a></p> <ul> <li>Download Corresponding w...
tensorflow|image-segmentation|tensorflow.js|bodypix
9
355,998
58,844,168
How does loss.backward() relate to the appropriate parameters of the model?
<p>I'm new in PyTorch and I'm having trouble understanding how <code>loss</code> knows to compute the gradients through <code>loss.backward()</code>? </p> <p>Sure, I understand that the parameters need to have <code>requires_grad=True</code> and I understand that it sets <code>x.grad</code> to the appropriate gradient...
<p>Loss is itself a tensor which is derived from the parameters of the network. A graph is implicitly constructed where each new tensor, including loss, points back to the tensors which were involved with it's construction. When you apply <code>loss.backward()</code> pytorch follows the graph backwards and populates th...
machine-learning|deep-learning|pytorch
2
355,999
58,735,104
Unstacking values in pandas groups into new columns
<p>I have a data frame roughly like this</p> <pre class="lang-python prettyprint-override"><code>data = [ {'user_id': 1, 'week': 1, 'score': 1}, {'user_id': 1, 'week': 2, 'score': 2}, {'user_id': 1, 'week': 2, 'score': 3}, {'user_id': 2, 'week': 1, 'score': 1}, {'user_id': 2, 'week': 1, 'score': 1}...
<p>you can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>groupby.cumcount()</code></a> with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.assign.html" rel="nofollow noreferrer"><co...
pandas|pandas-groupby
4