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
373,300
65,897,764
Converting hh:mm:ss to float for further calculations
<p>I need to convert my column with records like 'hh:mm:ss' to float format in order to make further calculations.</p> <p>In excel it is done in very simple way, you just multiply 'hh:mm:ss' by 24, but in Python it doesn't work out. I'm new to Python, need your help.</p> <p>Any idea?</p> <p>My Dataframe:</p> <pre><code...
<p>You can use below logic to find the time difference in seconds and then convert it into hours</p> <pre><code>import datetime as d lis = ['01:36:01', '00:02:18', '02:59:40', '04:16:30'] start_dt = dt.datetime.strptime(&quot;00:00:00&quot;, '%H:%M:%S') [float('{:0.3f}'.format((dt.datetime.strptime(time, '%H:%M:%S') - ...
python|pandas|dataframe
2
373,301
65,729,110
Finding the mean of a data column for a specified date-time range in pandas (python)
<p>New to this forum and to coding in general, so I apologize if this is a repeat question, will delete if so!</p> <p>I'm currently working with pandas in python and attempting to find a mean value within one of my data frame columns.</p> <p>I've created my dataframe, and called it 'data': <code>data=pd.DataFrame()</...
<p>Since you made it a datetime column you can easily use <code>.loc</code> to focus on a date range:</p> <pre><code>df.loc[(df['Dates'] &gt;= datetime(2020, 7, 21) &amp; df['Dates'] &lt;= datetime(2021, 1, 14)), 'col_to_mean'].mean() </code></pre> <p>where:</p> <ul> <li><code>'Dates'</code> is the name of the column w...
python|pandas|dataframe|datetime|mean
1
373,302
65,486,078
How to find the len() of a tf.Dataset
<p>I have started using the <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset" rel="nofollow noreferrer"><code>tf.data.Dataset</code></a> as a way to load data into keras models, as they appear to be much faster than keras' <code>ImageDataGenerator</code> and much more memory efficient than training o...
<h3>tl;dr</h3> <p>Unfortunately <code>tf.data.Dataset</code> is a generator and there is <strong>no</strong> inherent way of finding its size.</p> <h3>But...</h3> <p>Generally speaking, when you use <code>.from_tensor_slices()</code> you have a way of knowing its size by the argument you add in this method, in your cas...
python|tensorflow|machine-learning|keras|deep-learning
1
373,303
65,819,399
Is there a function in PyTorch for matrix left division?
<p>MATLAB has the backslash &quot;\&quot; operator. SciPy has &quot;lsqr.&quot; Does PyTorch have an equivalent operator that solves systems of linear equations?</p> <p>Specifically, I need to solve the matrix equation for <code>A*X=B</code> for <code>A</code>, and I need autograd to be able to backpropagate error thro...
<p>There is no <code>\</code> operator in <em>Python</em>. The closest you will get to is <em>Scipy</em>'s implementation: <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.linalg.lsqr.html" rel="nofollow noreferrer"><code>scipy.sparse.linalg.lsqr</code></a>.</p> <p>You can either use</p> <ul> ...
python|pytorch|linear-regression
-1
373,304
65,778,569
Drop or modify consecutive duplicate rows
<p>Suppose we have a DataFrame with two types of data: <code>float</code> and <code>ndarray</code> (shape is always <code>(2,)</code>):</p> <pre class="lang-py prettyprint-override"><code>data = [ 0.1, np.array([1.0, 0.1]), np.array([1.0, 0.1]), np.array([1.0, 0.1]), 0.1, 0.1, np.array([0.1, 1.0]), 1.0 ] df = p...
<h1>Step 1: Drop consecutive equal floats</h1> <p>To check whether 2 elements of a row are equal floats, define the following function:</p> <pre><code>def equalFloats(row): if (type(row.A).__name__ == 'float') and (type(row.B).__name__ == 'float'): return row.A == row.B return False </code></pre> <p>The...
python|pandas|duplicates
0
373,305
65,565,809
Pandas get row if column is a substring of string
<p>I can do the following if I want to extract rows whose column &quot;A&quot; contains the substring &quot;hello&quot;.</p> <pre><code>df[df['A'].str.contains(&quot;hello&quot;)] </code></pre> <p>How can I select rows whose column is the substring for another word? e.g.</p> <pre><code>df[&quot;hello&quot;.contains(df[...
<p>IIUC, you could apply <a href="https://docs.python.org/3/library/stdtypes.html#str.find" rel="nofollow noreferrer">str.find</a>:</p> <pre><code>import pandas as pd df = pd.DataFrame(['hell', 'world', 'hello'], columns=['A']) res = df[df['A'].apply(&quot;hello&quot;.find).ne(-1)] print(res) </code></pre> <p><strong>...
pandas
1
373,306
65,504,099
How to fill data from similar columns into a particular column(pandas)?
<p>I have a script that converts files.</p> <pre><code>import pandas as pd df = pd.read_csv(&quot;sample1.csv&quot;) final_df = df.reindex(['id','name','email'],axis=1) final_df.to_csv(&quot;output.csv&quot;, index = False) </code></pre> <p>sample1.csv</p> <pre><code>|name|email|id| |--| -- | -- | </code></pre> <p>...
<p>Select the target columns, then append to the target DataFrame.</p> <pre class="lang-py prettyprint-override"><code>dfn = pd.DataFrame(columns=['id', 'name', 'email']) for df in [df1, df2, df3]: # select columns cond_list = [ df.columns =='id', df.columns.str.contains('name|a...
python|python-3.x|pandas|dataframe|numpy
1
373,307
65,572,924
When should I use .copy()
<p>I know that for the following:</p> <pre><code>a=1 b=a a=4 </code></pre> <p>It assigns <code>1</code> to <code>a</code> and then <code>a</code> to <code>b</code> followed by changing the value of <code>a</code> to <code>4</code> as the last step.<br /> Here once the value of <code>a</code> is changed to <code>4</code...
<p>In the first &amp; second cases, you have assigned a single value (scalar) to <code>b</code>.</p> <p>In the third case, you've assigned a <a href="https://numpy.org/doc/stable/glossary.html#term-view" rel="nofollow noreferrer">view</a> based on the slice <code>0:2</code> of <code>a</code> to <code>b</code> (see <a h...
python|numpy
3
373,308
65,808,291
TensorFlow - Jupyter Lab -Failed to load the native TensorFlow runtime
<p>I started using TensorFlow but I have below error after I try to install TensorFlow and keras in python3.8 on Jupyter notebook. Can you please help me, I am using Python 3.8.1 64 bit.</p> <p><strong>I type this:</strong></p> <pre><code>import tensorflow as tf </code></pre> <p><strong>Output:</strong></p> <pre><code>...
<pre><code>#check current python version python --version #Create the virtual environment conda create -n tf python=PYTHON_VERSION #Activate the tf environment conda activate tf #Install Jupyter notebook on tf Env conda install jupyter #Launch jupyter notebook jupyter notebook #Install Tensorflow on Jupter notebook p...
python|python-3.x|tensorflow
0
373,309
65,808,646
Pandas, insert datetime values that increase one hour for each row
<p><a href="https://i.stack.imgur.com/ASyMG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ASyMG.png" alt="enter image description here" /></a></p> <p>I made predictions with an Arima model that predict the next 168 hours (one week) of cars on the road. I also want to add a column called &quot;datet...
<p>You can do:</p> <pre><code>x=pd.to_datetime('2021-01-01 00:00') y=pd.to_datetime('2021-01-07 23:59') pd.Series(pd.date_range(x,y,freq='H')) </code></pre> <p>output:</p> <pre><code>pd.Series(pd.date_range(x,y,freq='H')) Out[153]: 0 2021-01-01 00:00:00 1 2021-01-01 01:00:00 2 2021-01-01 02:00:00 3 202...
python|pandas|dataframe
6
373,310
65,680,685
Numpy filtering using array
<p>I know this has been asked before but there doesn't seem to be anything for my specific use-case.</p> <p>I have a numpy array <code>obs</code> which represents a color image and has shape <code>(252, 288, 3)</code>.</p> <p>I want to convert every pixel that is not pure black to pure white.</p> <p>What I have tried i...
<p>Boolean indexing like <code>obs[obs != [0, 0, 0]]</code> return a 1D array with all the elements from <code>obs</code> that satisfy the given condition. Look at the follwoing example:</p> <pre><code>obs = np.array([ [[88, 0,99], [ 0, 0, 0]], [[ 0, 0, 0], [88,77,66]] ]) </code></pre> <p><code>obs != [0, 0, 0]</...
python|arrays|numpy|image-processing|slice
5
373,311
65,891,437
Convert a set of pandas dataframes in a list
<p>I am trying to convert a set of <code>pandas</code> dataframes into an unique list,</p> <p>Here's what I got so far:</p> <pre><code>import pandas as pd df1= pd.DataFrame(data={'col1': [1, 2, 5], 'col2': [3, 4, 4]}) df2 = pd.DataFrame(data={'col3':[1,2,3,4,5], 'col4':[1,2,'NA', 'NA', 'NA'], 'col5':['John', 'Mary', ...
<p>The use of <code>list()</code> is incorrect here as that doesn't group the arguments into a list. You can instead just use <code>[]</code>:</p> <pre><code>df_list = [df1, df2, df3] </code></pre> <p>But a <code>list</code> cannot be indexed with a name, so you maybe want a <code>dict</code>:</p> <pre><code>df_dict =...
python|pandas|list|dataframe
1
373,312
65,733,754
How to split data in a double groupby dataframe?
<p>I have a big dataframe, there are two index columns for it- 'date' and 'con'</p> <pre><code>In [28]: df = pd.read_csv('~/futures_min_all.csv') In [29]: df Out[29]: open close high low tvr oi vol ticker date tme con 0 2854.0 2850.0 2854.0 2850.0 5696.0 1226 2 ...
<p>Here is modified solution for first 70% of unique rows, if order is not important change <code>pd.unique</code> to <code>set</code>s:</p> <pre><code>f = lambda x: x.head(int(len(pd.unique(x['Date'])) * -.7)) df1 = df.groupby('con',group_keys=False).apply(f).reset_index(drop=True) </code></pre> <p>Last filter all not...
python|pandas
1
373,313
65,774,822
How do I generate id column based on row values in python?
<p>It would be great if someone could help me to address below concern.</p> <p><a href="https://i.stack.imgur.com/5fBj7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5fBj7.png" alt="enter image description here" /></a></p> <p>How do I populate ID column based on values in respect row for all column...
<p>Using hashlib, you could take the dictionary of row values and translate that into an md5 hash.</p> <pre><code>import hashlib df['Id'] = [hashlib.md5(str(x).encode('utf-8')).hexdigest() for x in df.T.to_dict().values()] </code></pre>
python|python-3.x|pandas
1
373,314
65,907,634
Centroid of N-Dimension dataset
<p>As I am new in python and in programming in general, my teacher gave me some work. Some of it is to work with the MNIST database of handwritten numbers. Each of the numbers is a vector of 728 components. The problem comes when I want to compute the centroid of each class. This is, the mean of every number in each of...
<p>You are using numpy arrays so you should take advantage of all it has to offer.</p> <p>If you have an array of 10 vectors with 728 <em>elements</em></p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.random.random((10,728)) &gt;&gt;&gt; a.shape (10, 768) </code></pre> <p>Just take the <a href="https:...
python|numpy|mnist|centroid|n-dimensional
0
373,315
65,820,385
Pandas: sum rows of random numbers
<p>I have the following code that makes a 100x100 dataframe of random integers:</p> <pre><code>import pandas as pd import numpy as np bin = [] cols = [] for i in range(1,101): cols.append(&quot;count_&quot; + str(i)) bin.append(i) df = pd.DataFrame(np.random.randint(1,10,(100, 100)), index=bin, columns=cols) ...
<pre><code>bin = [] cols = [] for i in range(1,21): cols.append(&quot;count_&quot; + str(i)) bin.append(i) df = pd.DataFrame(np.random.randint(1,10,(20, 20)), index=bin, columns=cols) for col in cols: df[col]=df[col].astype(int) print(df.head()) fig,ax =plt.subplots(figsize=(16,8)) for item in df[cols].su...
python|pandas|python-3.8
0
373,316
65,757,507
Python-Apply Asset value and volatility calculation function for each row in csv file
<p>I imported a csv file and calculate asset value and volatility of a stock.</p> <pre><code>df = pd.read_csv (r'test.csv') df['ret_col'] = np.log(df.price) - np.log(df.price.shift(1)) df['sigma_e'] = np.std(df.ret_col) T = 1 </code></pre> <p>My function is:</p> <pre><code>def equation(x): d1 = (np.log(x[0]/df.face...
<p>I put the function after the loop so it works fine. Thank you for your hint.</p> <p>for i, row in df.iterrows():</p> <pre><code>def equation(x): d1 = (np.log(x[0]/row[&quot;default_point&quot;]) + (row[&quot;arf_rate&quot;]+x[1]**2/2)*T)/(x[1] * np.sqrt(T)) d2 = d1 - x[1] * np.sqrt(T) res...
python|pandas|scipy-optimize-minimize
0
373,317
65,536,454
Convert type str (with number and words) column into int pandas
<p>I have a column that contains type str of both numbers and words:</p> <p>ex.</p> <pre><code>['2','3','Amy','199','Happy'] </code></pre> <p>And I want to convert all &quot;str number&quot; into int and remove (the rows with) the &quot;str words&quot;.</p> <p>So my expected output would be a list like below:</p> <pre>...
<p>As you mentioned you have a column (a series), so let's say it's called <code>s</code>:</p> <pre><code>s = pd.Series(['2', '3', 'Amy', '199', 'Happy']) </code></pre> <p>Then after assigning, just do <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_numeric.html" rel="noreferrer"><code>pd....
python|pandas
10
373,318
65,694,449
tf.test.is_gpu_available() return false
<p>My tensonflow version is 2.3.0, Cuda is 10.1 and 10.0. I have different version cudnn for each cuda 10.1 and 10.0. I set up path like this:<a href="https://i.stack.imgur.com/DrdMY.jpg" rel="nofollow noreferrer">path for cuda</a></p> <p>when I run code in CMD like this:</p> <pre><code>Python 3.6.4 |Anaconda, Inc.| (d...
<p>On windows Os, Tensorflow-GPU setup, follow these steps</p> <p>Add the CUDA®, CUPTI, and cuDNN installation directories to the %PATH% environmental variable. For example, if the CUDA® Toolkit is installed to C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1 and cuDNN to C:\tools\cuda, update your %PATH% to ma...
python|tensorflow|tensorflow2.0
1
373,319
65,610,636
Pandas: Sort groups and sort within group
<p>My dataframe <code>df</code> contains products which have an EAN, an earlier and later date, 'yes' and 'no' labels and values.</p> <pre><code>EAN-Unique Date Start Value 3324324 2019-04-30 no 0.11 3324324 2018-06-01 yes 56.03 asd2343 2015-03-23 yes 8.02 asd2343 2015-07-11...
<p>create an auxiliary column <code>seq</code> to store group order by Start Value</p> <pre><code>group_order = df.sort_values(['Start', 'Value'], ascending=[False, True])['EAN-Unique'].unique() seq_map = dict(zip(group_order, range(len(group_order)))) df['seq'] = df['EAN-Unique'].map(seq_map) df.sort_values(['seq', '...
python|pandas|sorting|pandas-groupby
2
373,320
65,572,984
explode list and get index values for each list
<ul> <li><p>original DataFrame <code>df</code></p> <pre><code> label value 0 a 1 1 a 2 2 b 3 3 a 4 4 b 5 </code></pre> </li> <li><p><code>ds = df.groupby('label')['value'].apply(list)</code></p> <pre><code>label a [1, 2, 4] b [3, 5] </code></pre> </li> <li><p><cod...
<p>First, get length of list in <code>value</code> then apply <a href="https://numpy.org/doc/stable/reference/generated/numpy.arange.html" rel="nofollow noreferrer"><code>np.arange</code></a> or <a href="https://docs.python.org/3.8/library/functions.html#func-range" rel="nofollow noreferrer"><code>range</code></a> on i...
python|pandas|dataframe
2
373,321
65,538,179
Pytorch torch.load ModuleNotFoundError: No module named 'utils'
<p>I'm trying to load a pretrained model with torch.load.</p> <p>I get the following error:</p> <pre><code>ModuleNotFoundError: No module named 'utils' </code></pre> <p>I've checked that the path I am using is correct by opening it from the command line. What could be causing this?</p> <p>Here's my code:</p> <pre><code...
<p><strong>EDIT</strong> this answer doesn't provide the answer for the question but addresses another issue in the given code</p> <p>the <code>.pth</code> file just stores the parameters of a model, not the model itself. When you want to load a model you will need the <code>.pt/-h</code> file and the python code of yo...
python|machine-learning|pytorch
3
373,322
65,732,046
How to convert a float numpy.ndarray to list?
<p>here is my code</p> <pre><code>import numpy a = numpy.arange(0.5, 1.5, 0.1, dtype=numpy.float64) print(a) print(a.tolist()) &gt;&gt;&gt;[0.5 0.6 0.7 0.8 0.9 1. 1.1 1.2 1.3 1.4] &gt;&gt;&gt;[0.5, 0.6, 0.7, 0.7999999999999999, 0.8999999999999999, 0.9999999999999999, 1.0999999999999999, 1.1999999999999997, 1.29999999...
<p>By the conversion via <code>.tolist()</code> you're not gaining or loosing any precision. You're just converting to another data type which chooses to represent itself differently. You seem to be thinking that by the conversion it turns the <code>0.8</code> into <code>0.7999999999999999</code>, but the situation is,...
python|arrays|list|numpy|numpy-ndarray
1
373,323
65,744,528
Sort Pandas DataFrame with list column
<p>I have a dataframe I created from a pivot table like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>mykey</th> <th>values1</th> <th>values2</th> <th>values3</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>[1,2,0]</td> <td>[2,3,5]</td> <td>[2,3,4]</td> </tr> <tr> <td>3</td> <td>[2,...
<p>You can explode all of the columns simultaneously with <code>df.apply(pd.Series.explode)</code> into a longer dataframe in preparation for sorting. Then, <code>.groupby</code> back into a list, now in the desired order:</p> <pre><code>import pandas as pd df = pd.DataFrame({'mykey' : [1, 3], 'values1' : [[1,2,0], [2,...
pandas|list|sorting|pivot
0
373,324
21,004,993
Pandas, concat Series to DF as rows
<p>I attempting to add a Series to an empty DataFrame and can not find an answer either in the Doc's or other questions. Since you can append two DataFrames by row or by column it would seem there must be an "axis marker" missing from a Series. Can anyone explain why this does not work?.</p> <pre><code>import Pandas...
<p>You were close, just transposed the result from <code>concat</code></p> <pre><code>In [14]: s1 Out[14]: 0 a 1 5 2 6 dtype: object In [15]: s2 Out[15]: 0 b 1 8 2 9 dtype: object In [16]: pd.concat([s1, s2], axis=1).T Out[16]: 0 1 2 0 a 5 6 1 b 8 9 [2 rows x 3 columns] </code></pre>...
python|pandas|concat|series
15
373,325
21,295,077
How to ensure get label for zero counts in python pandas pd.cut
<p>I am analyzing a DataFrame and getting timing counts which I want to put into specific buckets (0-10 seconds, 10-30 seconds, etc).</p> <p>Here is a simplified example:</p> <pre><code>import pandas as pd filter_values = [0, 10, 20, 30] # Bucket Values for pd.cut #Sample Times df1 = pd.DataFrame([1, 3, 8, 20], co...
<p>You can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.reindex.html" rel="nofollow">reindex</a> by the categorical's levels:</p> <pre><code>In [11]: pd.value_counts(out).reindex(out.levels, fill_value=0) Out[11]: (0, 10] 3 (10, 20] 1 (20, 30] 0 dtype: int64 </code></pre>
pandas|ipython
3
373,326
21,336,669
Appending 3d array into 4d array, the 4th dimension being number of 3D arrays
<p>In the process of MRI image analysis, I would like to "mask" a time-series image as a part of pre-processing. Time-series Images are 4D (the 4th dimension is time at which the image was taken- x,y,z,t). Since my mask is a 3D array (x,y,z) I would like to duplicate 3D for all time-series images so that I can mask the...
<p>It's difficult to answer your question without more detail. But it sounds like you're confronting a problem like this:</p> <pre><code>&gt;&gt;&gt; a = numpy.arange(2 * 3 * 4 * 5).reshape(2, 3, 4, 5) &gt;&gt;&gt; mask = a[0,...] &gt; 29 &gt;&gt;&gt; numpy.ma.MaskedArray(a, mask) Traceback (most recent call last): ...
python|arrays|image-processing|numpy
1
373,327
21,237,833
Quit Python program when it hits memory limit
<p>I have a couple of Python/Numpy programs that tend to cause the PC to freeze/run very slowly when they use too much memory. I can't even stop the scripts or move the cursor anymore, when it uses to much memory (e.g. 3.8/4GB) Therefore, I would like to quit the program automatically when it hits a critical limit of m...
<p>You could limit the process'es memory limit, but that is OS specific.</p> <p>Another solution would be checking value of <code>psutil.virtual_memory()</code>, and exiting your program if it reaches some point.</p> <p>Though OS-independent, the second solution is not Pythonic at all. Memory management is one of the...
python|numpy
5
373,328
63,496,246
Imputing values from list into Pandas data frame
<p>I have a Pandas data frame that I would like to update a column. Currently the format is like with many many lines. If the value equals D I would like to random choose from a list to replace that value with. For example:</p> <pre><code>Values A B C D my_list = [&quot;E&quot;, &quot;F&quot;, &quot;G&quot;] df['V...
<p>You can assign</p> <pre><code>m = df['Values'].str.contains(&quot;D&quot;) df.loc[m,'Values']=np.random.choice(my_list,m.sum()) df Out[27]: Values 0 A 1 B 2 F 3 E </code></pre>
python|pandas
0
373,329
63,738,328
Pandas merge list with same id row wise
<p>How to concatenate list type column row wise in pandas? For example see below-</p> <p>Before,</p> <pre><code>1 a [a,b,c] 1 b [a,d] </code></pre> <p>After,</p> <pre><code>1 b [a,b,c,d] </code></pre> <p>I did column wise list concatenating like below,</p> <pre><code>df['all_poi'] = df['poi_part1'] + df['poi_p...
<p>You can create sets in custom function in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.agg.html" rel="nofollow noreferrer"><code>GroupBy.agg</code></a>:</p> <pre><code>f = lambda x: list(set(z for y in x for z in y)) df = df.groupby(['location_id', 'city'])['all_poi'...
python|pandas
3
373,330
63,329,291
Jupiter, unable to reset data frame index
<p><a href="https://i.stack.imgur.com/CwtQm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CwtQm.jpg" alt="enter image description here" /></a></p> <p>The above table is obtained after filtering dataframe (df).</p> <p>As mentioned below, When I tried to remove old index it give no result,</p> <pre><...
<p>We can not chain <code>reset_index()</code> and <code>inplace=True</code> with filter function</p> <pre><code>df = df.rename(dict(zip(df.index[:6],range(6))) </code></pre>
pandas|jupyter-notebook
1
373,331
63,602,307
I am not able to correctly assign a value to a df row based on 3 conditions (checking values in 3 other columns)
<p>I am trying to assign a proportion value to a column in a specific row inside my df. Each row represents a unique product's sales in a specific month, in a dataframe (called testingAgain) like this:</p> <pre><code> Month ProductID(SKU) Family Sales ProporcionVenta 1 1234 ...
<p>Generally, in Pandas (even Numpy), unlike general purpose Python, analysts should avoid using <code>for</code> loops as there are many vectorized options to run conditional or grouped calculations. In your case, consider <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html#transformation" re...
python|pandas|dataframe
1
373,332
63,346,447
How to pick part of a string in a column with multiple values
<p>I have a .tsv Dataframe with a specific column with more than one value separated by commas. It looks like this:</p> <pre><code> Col1 Col2 Col3 1 star1 HIP1, KOI1, Gaia1 3.4 2 star2 HIP2, KOI2, Gaia2 4.3 3 star3 HIP3, KOI3, Gaia3 7.2 </code></pre> <p>My objective is to take only p...
<p>You could use <code>pd.Series.str.extract</code> too:</p> <pre><code>df['Col2']=df['Col2'].str.extract('.*, (K.*), .*') </code></pre> <hr /> <p>Same as this, with <code>pd.Series.str.split</code>:</p> <pre><code>df['Col2']=df['Col2'].str.split(', ').str[1] </code></pre> <hr /> <p>Output:</p> <pre><code>df Col1 ...
python|pandas|dataframe
2
373,333
63,642,403
Filter rows in pandas, column with delimitor
<p>I have problem with a filter in a dataframe, I have several columns that have values separeted by (,). I need filter if one of these values is greater than a 3 (for the first column) and for 8 in the second column (the values are not sorted, and I have NaN in some rows)</p> <p>Example of df:</p> <pre><code>data = {'...
<p>Then let us use <code>split</code> with <code>any</code></p> <pre><code>s1 = df.Filter1.str.split(',',expand=True).astype(float).gt(3).any(1) s2 = df.Filter2.str.split(',',expand=True).astype(float).gt(8).any(1) newdf = df[s1 &amp; s2] newdf Out[36]: ID Filter1 Filter2 1 2 1,3,5 7,13 3 4 7,5 9,15,18...
python|pandas|dataframe
1
373,334
63,370,246
pandas dataframe-python check if string exists in another column ignoring upper/lower case
<p>I have the same dataframe as i asked in (<a href="https://stackoverflow.com/q/62603123/13666184">pandas dataframe check if column contains string that exists in another column</a>)</p> <pre><code>Name Description Am Owner of Am BQ Employee at bq JW Employee somewhere </code></pre> <p>...
<p>Use <code>.lower()</code> to make it case-agnostic:</p> <pre><code>df[df.apply(lambda x: x['Name'].lower() in x['Description'].lower(), axis=1)] </code></pre> <p>Note that this will consider <code>&quot;am&quot;</code> as a match on <code>&quot;amy&quot;</code>. You may wish to use word boundaries to prevent this:</...
python|pandas|dataframe
4
373,335
63,422,495
Histogram with double bars
<p>I would like to plot a histogram that shows the mean of the columns 'amb_o', 'intel_o', 'sinc_o', 'fun_o', 'attr_o', 'sinc_o' across the 'match' column. So for match(1) vs no match(0) I would like to see the mean of 'amb_o' next to each other, and same with the other 5 columns. In other words, I want to see the aver...
<ol> <li>calculate the means</li> <li>manipulate row and column multi indexes to get data set</li> <li>plot()</li> </ol> <pre><code>dating = pd.DataFrame({'amb_o': [7, 8, 5], 'intel_o': [5, 9, 2], 'sinc_o': [8, 9, 2], 'fun_o': [6, 9, 5], ...
python|pandas|plotly
0
373,336
63,472,524
Plotly.py bug using discrete colour data on stacked bar chart with customdata in hover text
<p>I have a Pandas DataFrame, <code>df</code> which I am using to populate a Plotly bar chart. For the sake of example, let's define <code>df</code> as the following:</p> <pre><code>import pandas, numpy import plotly.express as px df = pandas.DataFrame.from_dict( { &quot;x&quot;: [&quot;John Cleese&quot;, ...
<p>It turns out the solution was relatively simple, and was my fault rather than being an issue with the source code itself (oh, the hubris of thinking that it wasn't my fault!)</p> <h3>The reason my code breaks</h3> <p>On running <code>px.bar()</code>, <code>plotly.express</code> creates a <code>plotly.graph_objs.Figu...
python|pandas|plotly|plotly-python
0
373,337
63,539,203
Check if any pandas dataframe column values are within another pandas dataframe column
<p>I have df1 with messy Company names:</p> <pre><code> messyCompany 0 google123xyz 1 amazon12345 2 amzn12345 3 mcdonalds inc 4 healthtech ltd </code></pre> <p>And df2 with clean Company names and corresponding keywords:</p> <pre><code> cleanCompany keywords ...
<p>I would use <code>str.extract</code> instead and <code>map</code> the results:</p> <pre><code>df = pd.DataFrame({'messyCompany': {0: 'google123xyz', 1: 'amazon12345', 2: 'amzn12345', 3: 'mcdonalds inc', 4: 'healthtech ltd'}}) ref = pd.DataFrame({'cleanCompany': {0: 'Amazon', 1: 'Amazon'}, 'keywords': {0: 'amazon', 1...
python|pandas|dataframe|apply
0
373,338
63,321,714
Python change the array's dimension from (n,1) for (n,)
<p>If I declare an array &quot;v&quot; whose shape is (3,100) when I want to change its values column by column making use a &quot;for&quot; python changes the dimension of &quot;v[:,i]&quot; for (3,) this is annoying and I can't make the change because at the left member it has a (3,) array and in the right, it has an...
<pre><code>In [379]: M = np.arange(12).reshape(3,4) </code></pre> <p>Indexing with a scalar reduced the dimension by one. That's a basic rule of indexing - in <code>numpy</code> and <code>python</code>.</p> <pre><code>In [380]: M[0,:] ...
arrays|numpy|spyder
1
373,339
63,681,031
Merge two column header and give a new name in MultiIndex Dataframe python/Add column above column names
<p>I have the initial dataframe :</p> <pre><code> r_id1 r_score1 rid2 r_score2 Rank ID1 ID2 1 A-1 id-1 1.23 id-34 6.78 2 A-1 id-9 2.34 id-45 3.45 3 A-2 id-8 3.56 id-32 4.56 4 A-3 id-6 4.35 id-10 3.98 5 ...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.extract.html" rel="nofollow noreferrer"><code>str.extract</code></a> for get numbers from columns names, add prefix and last assign back with original columns for <code>MultiIndex in columns</code>:</p> <pre><code>print ...
python|python-3.x|pandas|dataframe|multi-index
1
373,340
63,479,086
How to filter multiple columns in a dataframe?
<p>I am trying to filter a dataframe columnwise with conditions specified by an array.</p> <p>Consider a dataframe with 2 columns.</p> <pre><code>index A B 1 100 200 2 110 210 3 120 220 </code></pre> <p>and a 2D array that specifies the range of values we want to filter for ea...
<p>Sometime use for loop is not bad, here we try <code>concat</code> the result of <code>between</code></p> <pre><code>newdf = df[pd.concat([df[y].between(*x) for x , y in zip(l, df.columns)],axis=1).all(1)] Out[52]: A B 1 110 210 </code></pre>
python|pandas|dataframe
1
373,341
63,666,851
Multi-label classification implementation
<p>So far I have used Keras Tensorflow to model image processing, NLP, time series prediction. Usually in case of having labels with multiple entries, so multiple categories the task was always to just predict to which class the sample belongs. So for example the list of possible classes was [car, human, airplane, flow...
<p>The loss function to be used is indeed the <code>binary_crossentropy</code> with a <code>sigmoid</code> activation.</p> <p>The <code>categorical_crossentropy</code> is not suitable for multi-label problems, because in case of the multi-label problems, the labels are not mutually exclusive. Repeat the last sentence: ...
python|tensorflow|keras|nlp|kaggle
4
373,342
63,501,136
Plotting annual mean and standard deviation in different colors for each year
<p>I have data for several years. I have calculated mean and standard deviation for each year. Now I want to plot each row with mean as a scatter plot and fill plot between the standard deviations that is mean plus minus standard deviation in different colors for different years.</p> <p>After using <code>df_wc.set_inde...
<p>That's a very good question that you have asked, and it did not have an easy answer. But if I had understood the problem correctly, you need a fill plot with different colours for each year. The upper bound and lower bound of the plot will be between mean + std and mean - std?</p> <p>So, I formed a custom time serie...
pandas|matplotlib|pandas-groupby
1
373,343
63,712,111
Appending arrays to matrix using Cupy
<p>I am using cupy to create a matrix and an array. I simply want to delete the first row of the matrix, and then append the new array to the matrix horizontally. I plan on putting this into a loop where I will continuously deleting the first row in the matrix and appending new arrays to the bottom. But I keep getting ...
<p>The <code>new_frame</code> array should have dimensions exactly the same as that of array <code>a</code> for it to be used in <code>cp.stack</code> function. In this case, you need to use <code>cp.concatenate</code> after changing the dimensions of <code>new_frame</code> to (1,100). The corrected script is given bel...
python|numpy|cupy
0
373,344
63,728,800
How to deal with different state space size in reinforcement learning?
<p>I'm working in <strong>A2C</strong> reinforcement learning where my environment has an increasing and decreasing in the number of agents. As a result of the increasing and decreasing the number of agents, the state space will also change. I have tried to solve the problem of changing the state space this way:</p> <...
<p>For the paper, I'm gonna give the same reference as in the <a href="https://ai.stackexchange.com/a/23315/37982">other post</a> already: <a href="http://proceedings.mlr.press/v87/vinitsky18a/vinitsky18a.pdf" rel="nofollow noreferrer">Benchmarks for reinforcement learning minmixed-autonomy traffic</a>.</p> <p>In this ...
python|tensorflow|reinforcement-learning
3
373,345
63,624,526
Tensorflow gradient returns nan or Inf
<p>I am trying to implement a WGAN-GP model using tensorflow and keras (for <a href="https://www.kaggle.com/mlg-ulb/creditcardfraud" rel="nofollow noreferrer">credit card fraud data from kaggle</a>).</p> <p>I mostly followed the sample code that is provided in <a href="https://keras.io/examples/generative/wgan_gp/" rel...
<p>So after much more digging into the internet, it turns out that this is because of the numerical instability of <code>tf.norm</code> (and some other functions as well).</p> <p>In the case of <code>norm</code> function, the problem is that when calculating its gradient, its value appears in the denominator. So <code>...
python|tensorflow|keras|deep-learning|generative-adversarial-network
4
373,346
63,670,324
pandas_udf giving error related to pyarrow
<p>I have dataframe where I want to get the lat_long for the given geolocation using polyline library in pysaprk</p> <pre><code>+-----------------+--------------------+----------+ | vid| geolocations| trip_date| +-----------------+--------------------+----------+ |58AC21...
<p>You are most likely getting this error because a <code>pandas_udf</code> takes a pandas Series as input and you are applying the <code>decode</code> function directly to this series, instead of applying it to the values within the pandas Series.</p> <p>E.g. in the example below, I expanded your lambda function a bit...
python|pandas|apache-spark|pyspark|pyarrow
0
373,347
63,668,258
Sorting dataframe by specific column names in Pandas
<p>How to sort pandas's dataframe by specific column names? My dataframe columns look like this:</p> <pre><code>+-------+-------+-----+------+------+----------+ |movieId| title |drama|horror|action| comedy | +-------+-------+-----+------+------+----------+ | | +-------+---...
<p>Sorting all columns after second column and add first 2 columns:</p> <pre><code>c = df.columns[:2].tolist() + sorted(df.columns[2:].tolist()) print (c) ['movieId', 'title', 'action', 'comedy', 'drama', 'horror'] </code></pre> <p>Last change order of columns by this list:</p> <pre><code>df1 = df[c] </code></pre> <p>A...
python|pandas
1
373,348
63,333,310
find closest row to other DataFrame and get index of that row
<p>I have two DataFrames,</p> <pre><code>df1 = payout 0 0.05 1 0.03 2 0.06 </code></pre> <p>and</p> <pre><code>df2 = value 0 0.0100 1 0.0275 2 0.0400 3 0.0500 4 0.0570 5 0.0610 </code></pre> <p>I would like <code>df1</code> to have a new column with the closest ro...
<p>Check with <code>merge_asof</code></p> <pre><code>df = pd.merge_asof(df1.sort_values('payout'), df2.reset_index().sort_values('value'), left_on='payout', right_on='value', direction='nearest') </code></pre>
python|pandas
3
373,349
63,687,673
Pandas dataframe values reassignment by index
<p>I have rand_df1:</p> <pre><code>np.random.seed(1) rand_df1 = pd.DataFrame(np.random.randint(0, 40, size=(3, 2)), columns=list('AB')) print(rand_df1, '\n') </code></pre> <pre><code> A B 0 37 12 1 8 9 2 11 5 </code></pre> <p>Also, rand_df2:</p> <pre><code>rand_df2 = pd.DataFrame(np.random.randint(0, 40,...
<p>Thanks to Henry Yik for his solution:</p> <pre><code>rand_df2.combine_first(rand_df1) </code></pre> <pre><code> A B 0 37 12 1 16 1 2 12 7 2 12 7 2 12 7 2 12 7 2 12 7 2 12 7 2 12 7 </code></pre> <p>Also, tested this with extra column in one dataframe, that doesn't appears in second dataframe and...
python|pandas|dataframe
0
373,350
63,655,467
How to extract dictionary and sub dictionary
<p>Here is an original dataframe of 2 rows consisting of ID and ColumnA. Some row may have one detail.</p> <pre><code>ID ColumnA 1 {'1': {'Order': '0', 'Result': ''}, '2': {'Order': 'Yellow', 'Result': 'Red'}, '3': {'Order': 'Clear', 'Result': 'Tight'}, '4': {'Order': '1.000-1.030', 'Result': '1.015'}...
<p>Extraction by looping on dictionary items:</p> <pre><code>import pandas as pd data = [ ['1', {'1': {'Order': '0', 'Result': ''}, '2': {'Order': 'Yellow', 'Result': 'Red'}, '3': {'Order': 'Clear', 'Result': 'Tight'}, '4': {'Order': '1.000-1.030', 'Result': '1.015'}}], ['2', {'1': {'Order': '...
python|pandas|dataframe|dictionary
1
373,351
63,580,969
Pandas series index as column name of dataframe
<p><strong>Task description</strong></p> <p>I have a pandas series as follows:</p> <pre><code> rank loc 0.0 AU 2 US 1 1.0 UK 1 AU 3 US 1 </code></pre> <p>I wish to make a DataFrame with rank as the column name and loc as the index. The desired ...
<p>Suppose this series is called S.</p> <p>First flatten it and convert to a dataframe and rename for easier access</p> <pre><code>df = pd.DataFrame(pd.DataFrame(S).to_records()) df.columns = ['rank', 'loc', 'counts'] </code></pre> <p>Now group by <em>loc</em>, and loop over each group and create a dictionary, with &qu...
python|pandas|dataframe
0
373,352
63,400,473
Pandas passing arguments to apply
<p>I'm trying to apply a function to a dataframe, creating a new column as a result, like so:</p> <pre><code>def defensive_weights(DSp=None,SGp=None,FCp=None): if dfcrop['opp_goals'] == 0: DInd = (DSp*2 + SGp + FCp) else: DInd = (DSp + SGp + FCp) return DInd dfcrop['IED'] = dfcrop['opp_...
<p>It appears you're calling the entire dataframe series from within the function. I don't think you want to do this. You should allow the function to take a parameter, and pass it to the conditional:</p> <pre><code>def defensive_weights(item, DSp=None,SGp=None,FCp=None): if item == 0: DInd = (DSp*2 + SGp +...
python|pandas
1
373,353
63,502,430
Why does regularization in pytorch and scratch code does not match and what is the formula used for regularization in pytorch?
<p>I have been trying to do L2 regularization on a binary classification model in PyTorch but when I match the results of PyTorch and scratch code it doesn't match, Pytorch code:</p> <pre><code>class LogisticRegression(nn.Module): def __init__(self,n_input_features): super(LogisticRegression,self).__init__() ...
<p>Great question. I dug a lot through <strong>PyTorch</strong> documentation and found the answer. The answer is very <strong>tricky</strong>. Basically there are <strong>two</strong> ways to calculate <strong>regulalarization</strong>. (For summery jump to the last section).</p> <p><a href="https://i.stack.imgur.com/...
python|pytorch|regularized
2
373,354
63,645,036
How to convert .hdf5 to .h5 keras model
<p>I have a pre-trained hdf5 model background removal model that I've used from <a href="https://github.com/aadityavikram/Background-Removal" rel="nofollow noreferrer">here</a>. I'm looking to convert it to h5 as <code>coremltools</code> converter requires that type.</p> <p>So far, the coremltools python script gives t...
<p>It's literally the same format, so you can change the extension by renaming the file to <code>.h5</code> and it should work fine.</p>
tensorflow|keras
7
373,355
63,600,850
Why re.findall only return first ten rows
<p>I try to match the string with using regex from 59k rows. Off course I expected the same 59k rows as the result. However the result only return first 10 rows.</p> <p>I feels this a silly questions, but still wondering what's wrong here.</p> <pre><code>y = str(data[['geometry']]) z = re.findall(&quot;(?&lt;=\()\d.*(?...
<p>You probably need <code>str.findall</code> with <code>tolist()</code></p> <p><strong>Ex:</strong></p> <pre><code>data['geometry'].str.findall(&quot;(?&lt;=\()\d.*(?=\))&quot;).tolist() </code></pre> <p><strong>Demo:</strong></p> <pre><code>df = pd.DataFrame({'geometry': ['aa (123) bb (1.5)', 'aa (123) bb (1.5)', 'aa...
python|python-3.x|regex|pandas|jupyter-notebook
1
373,356
63,471,781
Making custom activation function in tensorflow 2.0
<p>I am trying to create a custom tanh() activation function in tensorflow to work with a particular output range that I want. I want my network to output concentration multipliers, so I figured if the output of tanh() were negative it should return a value between 0 and 1, and if it were positive to output a value bet...
<p>I suggest you <code>tf.keras.backend.switch</code>. Here a dummy example</p> <pre><code>import numpy as np import tensorflow as tf from tensorflow.keras.layers import * from tensorflow.keras.models import * from tensorflow.keras import backend as K def output_activation(x): return K.switch(x &gt;= 0, tf.math.ta...
tensorflow|keras|tensorflow2.0|activation-function
2
373,357
63,419,259
How to group together rows of Pandas Dataframe with same values in first 2 columns by summing values in the 3rd column?
<p>I have a dataframe of the form:</p> <p><a href="https://i.stack.imgur.com/dOlEc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dOlEc.png" alt="enter image description here" /></a></p> <p>For same values of col1 and col2 (for example, A B), I want to add all values in the col3 of the dataframe su...
<p>You just need to do this, <code>False</code> instead of <code>True</code>:</p> <pre><code>df.groupby(['col1', 'col2'], axis=0, as_index=False).sum() </code></pre>
python|python-3.x|pandas|dataframe|pandas-groupby
6
373,358
63,372,272
How can I add position of similar records to two separate csv files?
<p>First, I just started with pandas and my task is that I have two csv files, I read them, compare and append which rows are they occupying in both files. I am using pandas DataFrame. Now I have to write it back to csv, append extra column with these positions. I am thinking about using dict or lists and append them a...
<p>If I understand you right you could:</p> <pre><code># list of the values in the common column list_common = df['common'].tolist() # Get the index of the values matching in the other dataframes matching_df1 = df.index[df1['Student'].isin(list_common)].tolist() matching_df2 = df.index[df2['Student'].isin(list_common)...
python|pandas|csv
0
373,359
63,583,365
Numpy - More efficient code to calculate metric
<p>I am trying to implement this metric <a href="https://i.stack.imgur.com/V7y16.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V7y16.png" alt="enter image description here" /></a></p> <p>I already managed to calculate NUBN with numpy operations so that is fast, but I can't find a way to escape pyth...
<p>The first step in speeding things up with numpy is to break up your sequence of operations into something that can be applied to an entire array. Let's start with an easy one: removing the comprehensions in the computation of <code>W</code>:</p> <pre><code>W = np.hypot(np.arange(-2, 3), np.arange(-2, 3)[:, None]) np...
python|performance|numpy
3
373,360
63,431,597
How to drop certain values within a multi-level index python pandas
<p>I have something similar to the following dataframe, <code>df</code>:</p> <pre><code>df full_name team rec_yards 0 Michael Thomas NO 1688 1 Chris Godwin NO 1333 2 DeAndre Hopkins NO 1165 3 Julio Jones NO 1316 4 Cooper Kupp NO ...
<p>I think this should work:</p> <pre><code># Make a sorted multi-index df_sorted = df.set_index(['team','rec_yards']).sort_index(ascending=False) # Add a dummy column containing all 1s df_sorted['count'] = 1 # Turn it into a ranking by team df_sorted['count'] = df_sorted.groupby('team')['count'].cumsum() # O...
python|pandas|dataframe|indexing
2
373,361
63,690,592
Extract data from column to new column after groupby
<p>I am trying to extract and split a column of data into two new columns. This is reasonably simple using <code>.str[xx:yy]</code></p> <p>However, I am getting an error when I am trying to complete the same after having run a <code>.groupby([&quot;xxx&quot;, &quot;yyy&quot;, &quot;zzz&quot;])[[&quot;aaa&quot;]].count(...
<p>I think using apply and then splitting the series item might solve what you are looking for!! Try this</p> <pre><code>DevReg_df[&quot;Language&quot;] = DevReg_df[&quot;Device Loc&quot;].apply(lambda x:x.split('_')[0]) </code></pre>
python|python-3.x|pandas|pandas-groupby
1
373,362
63,456,418
Keras: ValueError: logits and labels must have the same shape ((None, 2) vs (None, 1))
<p>I have been using the famous dogs-vs-cats kaggle dataset and trying to come up with my own CNN Model. I'm new to using the <code>image_dataset_from_directory</code> method to import the dataset after configuring it into two folders that contain the cat and dog images separately.</p> <p>Here is the code for the model...
<p>I finally found the solution to my question! I managed to train the model by setting the loss function to <code>sparse_categorical_crossentropy</code> instead of <code>binary_crossentropy</code>. Then I also changed the activation function of the last layer to <code>softmax</code> that was <code>sigmoid</code> when ...
python|tensorflow|keras
14
373,363
63,479,920
How to make custom code in python utilize GPU while using Pytorch tensors and matrice functions
<p>I've created a CNN from scratch only using Pytorch tensors and matrix operation functions in the hope of utilizing GPU. To my surprise, the GPU stays 0% utilized and my training doesn't seem to be faster than running on my cpu.</p> <p><strong>Before Training:</strong></p> <p><a href="https://i.stack.imgur.com/r1gaK....
<p>You have to move your model and data to GPU using</p> <pre><code>model.cuda() # and x = x.cuda() y = y.cuda() </code></pre> <p>You seem to be doing this with-in the calls of forward and backwards. To make sure the model is going on to GPU, monitor the GPU usage continually using shell command</p> <p><code>watch -n ...
machine-learning|pytorch|gpu|conv-neural-network
0
373,364
21,463,589
Pandas: Chained assignments
<p>I have been reading this <a href="http://pandas-docs.github.io/pandas-docs-travis/indexing.html#indexing-view-versus-copy" rel="noreferrer">link</a> on "Returning a view versus a copy". I do not really get how the <strong>chained assignment</strong> concept in Pandas works and how the usage of <code>.ix()</code>, <c...
<p>The point of the <code>SettingWithCopy</code> is to warn the user that you <em>may</em> be doing something that will not update the original data frame as one might expect.</p> <p>Here, <code>data</code> is a dataframe, possibly of a single dtype (or not). You are then taking a reference to this <code>data['amount'...
python|pandas|copy|chained-assignment
30
373,365
21,605,927
Why doesn't setup_requires work properly for numpy?
<p>I wanted to create a <code>setup.py</code> file that automatically resolves a build-time dependency to numpy (for compiling extensions). My first guess was to use <code>setup_requires</code> and subclass a command class to import the numpy module:</p> <pre><code>from setuptools import setup, Extension from distutil...
<p>Figured out, that a proper initialization of the numpy module is prevented by a check for <code>__NUMPY_SETUP__</code> inside <code>numpy/__init__.py</code>:</p> <pre><code>if __NUMPY_SETUP__: import sys as _sys _sys.stderr.write('Running from numpy source directory.\n') del _sys else: # import subo...
python|numpy|setuptools
11
373,366
21,896,051
How to get Python Class to Return Some Data and not its Object Address
<h2>Context:</h2> <p>Using the following:</p> <pre><code>class test: def __init__(self): self._x = 2 def __str__(self): return str(self._x) def __call__(self): return self._x </code></pre> <p>Then creating an instance with <code>t = test()</code></p> <p>I see how to use <code>_...
<p><code>__repr__</code> is intended to be the literal <strong>representation</strong> of the object.</p> <p>Note that if you define <code>__repr__</code>, you don't have to define <code>__str__</code>, if you want them both to return the same thing. <code>__repr__</code> is <code>__str__</code>'s fallback.</p> <pre>...
python|oop|methods|pandas|representation
8
373,367
21,887,138
Iterate over the output of `np.where`
<p>I have a 3D array and use <code>np.where</code> to find elements that meet a certain condition. The output of <code>np.where</code> is a tuple of three 1D arrays, each giving the indices along a single axis. I'd like to iterate over this output and print out the index of each point in the matrix that met the conditi...
<p>Use <code>zip</code></p> <pre><code>indices = zip(*np.where(myarray == 0)) </code></pre> <p>Then you can do</p> <pre><code>for i, j, k in indices: print ... </code></pre> <p>For example,</p> <pre><code>In [1]: x = np.random_integers(0, 1, (3, 3, 3)) In [2]: np.where(x) # you want np.where(x==0) Out[2]: (arr...
python|numpy|multidimensional-array|indexing
9
373,368
21,768,045
Pandas time series indexing -- re
<p>I have a pandas dataframe indexed by time:</p> <pre><code>&gt;&gt;&gt; dframe.head() aw_FATFREEMASS raw aw_FATFREEMASS sym TIMESTAMP 2011-12-08 23:13:23 139.3 H 2011-12-08 23:12:18 139.2 H 2011-12-08 22:31:53 139.2 ...
<p>docs are <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#partial-string-indexing" rel="nofollow">here</a></p> <p>This is called partial string indexing. In a nutshell, providing a string will get you results that 'match', e.g. they are included in the specified interval, while if you specify a ...
python|pandas|time-series
3
373,369
21,727,199
Python convex hull with scipy.spatial.Delaunay, how to eleminate points inside the hull?
<p>I have a list of 3D points in a np.array called <code>pointsList</code>, values are <code>float</code> :</p> <pre><code>[[1., 2., 10.], [2., 0., 1.], [3., 6., 9.], [1., 1., 1.], [2., 2., 2.], [10., 0., 10.], [0., 10., 5.], ... etc. </code></pre> <p>This code makes a Delaunay triangulation of the cloud of poi...
<p>The convex hull is a subgraph of the Delaunay triangulation. </p> <p>So you might just use <a href="http://docs.scipy.org/doc/scipy-dev/reference/generated/scipy.spatial.ConvexHull.html" rel="noreferrer"><code>scipy.spatial.ConvexHull()</code></a>, e. g.</p> <pre><code>from scipy.spatial import ConvexHull cv = Con...
python|numpy|scipy|convex-hull|delaunay
15
373,370
21,635,915
Why does pandas apply calculate twice
<p>I'm using the apply method on a panda's DataFrame object. When my DataFrame has a single column, it appears that the applied function is being called twice. The questions are why? And, can I stop that behavior?</p> <p><strong>Code:</strong></p> <pre><code>import pandas as pd def mul2(x): print ('hello') r...
<p>This behavior is intended, as an optimization.</p> <p>See the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="noreferrer">docs</a>:</p> <blockquote> <p>In the current implementation apply calls func twice on the first column/row to decide whether it can take a f...
python|pandas|apply
16
373,371
21,761,726
numpy einsum with '...'
<p>The code below is meant to conduct a linear coordinate transformation on a set of 3d coordinates. The transformation matrix is <code>A</code>, and the array containing the coordinates is <code>x</code>. The zeroth axis of <code>x</code> runs over the dimensions x, y, z. It can have any arbitrary shape beyond that.</...
<p>Yep, it's a bug. It was fixed in this pull request: <a href="https://github.com/numpy/numpy/pull/4099" rel="nofollow">https://github.com/numpy/numpy/pull/4099</a></p> <p>This was only merged a month ago, so it'll be a while before it makes it to a stable release.</p> <p><strong>EDIT</strong>: As @hpaulj mentions i...
python|numpy
3
373,372
24,729,010
Convert R Matrix to Pandas Dataframe
<p>I'm trying to convert an R matrix to a pandas dataframe. I am using:</p> <pre><code>import pandas.rpy.common as com df = com.convert_to_r_dataframe(r_matrix) </code></pre> <p>And I get:</p> <pre><code>TypeError: 'float' object cannot be interpreted as an index </code></pre> <p>Strangely enough this use case is o...
<p>Just use <code>numpy.array()</code>:</p> <pre><code>from rpy2 import robjects m = robjects.reval("matrix(1:6, nrow=2, ncol=3)") import numpy as np a = np.array(m) </code></pre>
python|r|matrix|pandas|rpy2
3
373,373
24,601,405
Why do statsmodels's correlation and autocorrelation functions give different results in Python?
<p>I need to obtain the correlation between two different series A and B as well as the autocorrelations of A and B. Using the correlation functions provided by statsmodels I got different results, it's not the same to calculate the autocorrelation of A and to calculate the correlation between A and A, Why are the resu...
<p>The two functions have different default arguments for the boolean <code>unbiased</code> argument. To get the same result as <code>acf(A, fft=True)</code>, use <code>ccf(A, A, unbiased=False)</code>.</p>
python|numpy|statsmodels
4
373,374
24,462,706
Pandas concatenate all elements of dataframe into single series
<p>There must be a simple answer to this, but for some reason I can't find it. Apologies if this is a duplicate question.</p> <p>I have a dataframe with shape on the order of (1000,100). I want to concatenate ALL items in the dataframe into a single series (or list). Order doesn't matter (so it doesn't matter what axi...
<p>This will yield a 1-dim numpy-array of the lowest-common dtype for all elements.</p> <pre><code>df.values.ravel() </code></pre>
python|pandas
3
373,375
24,692,394
Select elements from an array using another array as index
<p>Say I have an array</p> <pre><code>A = array([[1,2,3], [4,5,6], [7,8,9]]) </code></pre> <p>Index array is </p> <pre><code>B = array([[1], # want [0, 1] element of A [0], # want [1, 0], element of A [1]]) # want [2, 1] elemtn of A </code></pre> <p>By this index array ...
<p>For answer completeness... Fancy indexing arrays are broadcast to a common shape, so the following also works, and spares you that final reshape:</p> <pre><code>&gt;&gt;&gt; A[np.arange(3)[:, None], B] array([[2], [4], [8]]) </code></pre>
python|arrays|numpy
5
373,376
24,580,543
how to show info about dataframe in canopy
<p>I'm using the free version of canopy v1.4.1. I have similar problem stated in here: <code>http://stackoverflow.com/questions/11361985/output-data-from-all-columns-in-a-dataframe-in-pandas</code> but instead of getting the information about data frames I'm getting the actual table with the data listed in table: </p> ...
<p>It looks like a couple things are happening - 1) you are using iPython (because Canopy does), so pandas defaults to HTML pretty-printing when it can, and 2) you want the info on the whole dataframe.</p> <p>To turn off the pretty-printing, do</p> <pre><code>import pandas as pd pd.set_option('display.notebook_repr_h...
python|pandas|ipython|dataframe|canopy
0
373,377
24,756,741
Numpy: Transform sparse matrix to ndarray
<p>I really couldn't google it. How to transform sparse matrix to ndarray?</p> <p>Assume, I have sparse matrix t of zeros. Then</p> <pre><code>g = t.todense() g[:10] matrix([[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]]) </code></pre> <p>instead of [0, 0, 0, 0, 0, 0, 0, 0, 0...
<p>Use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.asarray.html" rel="nofollow"><code>np.asarray</code></a>:</p> <pre><code>&gt;&gt;&gt; a = np.asarray(g) &gt;&gt;&gt; a array([[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]]) </cod...
python|numpy|matrix|sparse-matrix
3
373,378
30,145,996
Get row numbers of rows matching a condition in numpy
<p>Suppose I have a numpy array like:</p> <pre><code>a = array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [3, 2, 1]]) </code></pre> <p>I want to check if the second element == 2. </p> <p>I know I can do this:</p> <pre><code>&gt;&gt;&gt; a[:,1]==2 array([ True, False, False, True], dtype=bool) </code></...
<p>Use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="noreferrer"><code>np.where</code></a> to return the indices:</p> <pre><code>In [79]: np.where(a[:,1]==2) Out[79]: (array([0, 3], dtype=int64),) </code></pre>
python|arrays|numpy
14
373,379
29,933,553
Pandas, matplotlib and plotly - how to fix series legend?
<p>I'm trying to create an interactive plotly graph from pandas dataframes.</p> <p>However, I can't get the <strong>legends</strong> displayed correctly.</p> <h2>Here is a working example:</h2> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt import plotly.plotly as py # sign into the ...
<p>Legends don't convert well from matplotlib to plotly.</p> <p>Fortunately, adding a plotly legend to a matplotlib plot is straight forward:</p> <pre><code>update = dict( layout=dict( showlegend=True # show legend ) ) py.iplot_mpl(fig, update=update) </code></pre> <p>See the full working <a href="...
python|pandas|matplotlib|plotly
3
373,380
29,940,382
100% area plot of a pandas DataFrame
<p>In <a href="http://pandas.pydata.org/pandas-docs/stable/visualization.html#area-plot" rel="noreferrer">pandas' documentation</a> you can find a discussion on <em>area plots</em>, and in particular stacking them. Is there an easy and straightforward way to get a 100% area stack plot like this one</p> <p><img src="ht...
<p>The method is basically the same as in <a href="https://stackoverflow.com/a/16899920/671013">the other SO answer</a>; divide each row by the sum of the row:</p> <pre><code>df = df.divide(df.sum(axis=1), axis=0) </code></pre> <p>Then you can call <code>df.plot(kind='area', stacked=True, ...)</code> as usual.</p> <...
python|pandas|plot
16
373,381
30,140,499
Pandas - Select rows of a dataframe that contains a certain regex in ANY column
<p>Good morning</p> <p>given a dataframe that contains text data such as:</p> <pre><code>df = pandas.DataFrame({ 'a':['first', 'second', 'third'], 'b':['null', 'third', 'first']}) </code></pre> <p>I can select rows that contain the word <code>'first'</code> by:</p> <pre><code>df.a.str.contains('first') | d...
<p>Why don't we use <code>applymap</code> on the entire data frame. This will be different than working the columns but would make it easier for your to apply if-else conditions to (I hope):</p> <pre><code>In [62]: l = ['first', 'second'] In [63]: df Out[63]: a b 0 first null 1 second third 2 th...
python|python-2.7|pandas
2
373,382
29,820,796
Overcoming broadcasting error for Legendre polynomails, scipy eval_legendre
<p>I am trying to evaluate the Legendre polynomial P_n(x) with scipy's special function </p> <pre><code>scipy.special.eval_legendre(n, x) </code></pre> <p>which allows you to evaluate a Legendre at certain points. I would then like to sum these Legendre polynomials together, \Sigma_n P_n(x). </p> <p>Begin by evaluat...
<p>This should do the job:</p> <pre><code>sum( [eval_legendre(x,matrix) for x in range(1,10)] ) </code></pre> <p>Each call to the <code>eval_legendre</code> function returns a matrix of the shape of the matrix you pass to it. So we can make a list of these matrices using list comprehension, and sum them as you sugges...
python|numpy|scipy
1
373,383
29,830,291
Aggregation in pandas dataframe on two separate columns
<p>I am trying to do aggregation on fields <code>cat1, cat2, cat3</code> on the following DataFrame. I need to <code>count the number of trials</code> and the <code>number of unique subjects</code> in each group. The code below does find the number of trials correct but the number of subject is not correct.</p> <pre>...
<p>You could <code>aggregate</code> on <code>ID</code> with <code>pd.Series.nunique</code> and get <code>count</code> from <code>trail</code></p> <pre><code>In [215]: (mydata.groupby(['cat1', 'cat2', 'cat3']) .agg({'ID': pd.Series.nunique, 'trial': 'count'}) .reset_index()) Out[215]: ...
python|pandas
2
373,384
30,042,938
Python/Pandas: replacing certain values in multiple columns of large dataset
<p>I have a small dataframe containing 320k rows and 450 of columns. There are some of lists with column numbers:</p> <pre><code>list1 = [1,3,5,...] list2 = [4,9,...] ... </code></pre> <p>My goal is to replace certain values in each column from current list and then to save it:</p> <pre><code>df[df[list1] &gt; 7] = ...
<p>It's possible this could be improved by keeping the file open, rather than opening the file each time in append mode:</p> <pre><code>with open(newFile, 'a') as f: for chunk in pd.read_csv(filePrev,chunksize=10000,header=None): chunk[chunk[list1] &gt;= 7] = np.nan chunk[chunk[list2] &gt;= 90] = n...
python|pandas|replace|dataframe|nan
1
373,385
30,072,562
Finding a local Maxima/minimum using python
<p>My code is based on a comment in: <a href="https://stackoverflow.com/questions/4624970/finding-local-maxima-minima-with-numpy-in-a-1d-numpy-array">Finding local maxima/minima with Numpy in a 1D numpy array</a></p> <p>It works, however it does not reproduce all the peaks for me. It always seems to miss the first pea...
<p>The problem seems to be originating in your original data. The first peak, unlike all the other ones, consists of the same value twice <code>-16329, -16329,</code>. Even after applying the Gauss filter this will still be a plateau rather than a peak.</p> <p>When you use <code>np.greater</code> as a comparator it fa...
python|numpy
1
373,386
30,099,823
python can't find numpy
<p>I was trying to follow the instruction from this link :<a href="http://www.thisisthegreenroom.com/2011/installing-python-numpy-scipy-matplotlib-and-ipython-on-lion/" rel="nofollow">http://www.thisisthegreenroom.com/2011/installing-python-numpy-scipy-matplotlib-and-ipython-on-lion/</a> However, it seems my python can...
<p>Seems like the version of <code>pip</code> you are using is using the default mac system-wide python interpreter <code>/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python</code> instead of the one installed in <code>/usr/local/bin</code>.</p> <p>I've pretty much experienced the same issues un...
python|python-2.7|numpy
2
373,387
53,743,704
element-wise multiplication - 'NoneType' object has no attribute '_inbound_nodes'
<p>It's a problem with code of Keras using Tensorflow.</p> <p>I have a simple network where I need to do an element-wise multiplication immediately after the input. This part of code is shown below. I always got the error:</p> <p>*** AttributeError: 'NoneType' object has no attribute '_inbound_nodes'</p> <p>My code:...
<p>You are operating your tensors outside of a layer. (Getting slices are operations too)</p> <p>You would need to take the slices <code>input_img[:,:,:,:,:,0]</code> and <code>input_img[:,:,:,:,:,1]</code> <strong>inside</strong> a layer. </p> <pre><code>masked = Lambda(lambda x: x[:,:,:,:,:,0]*x[:,:,:,:,:,1])(input...
python|tensorflow|keras|layer
1
373,388
53,603,093
How do return the number of times a value in a column does not line up with another value in another column?
<p>I have a dataframe df :</p> <pre><code>&gt;&gt;&gt; df user_id group landing_page converted 12345 control old_page 0 12346 treatment new_page 1 12347 control new_page 1 12345 treatment ...
<p>IIUC, you are looking for</p> <pre><code>&gt;&gt;&gt; ((df['group'] == 'treatment') &amp; (df['landing_page'] != 'new_page')).sum() 2 </code></pre> <p>Details:</p> <pre><code>&gt;&gt;&gt; df['group'] == 'treatment' 0 False 1 True 2 False 3 True 4 True Name: group, dtype: bool &gt;&gt;&gt; &gt;&...
python|pandas
1
373,389
53,747,396
Load data and average in single operation
<p>I'm trying to load data of the form shown below into a dataframe.</p> <pre><code>popSize: 1000 numSurvivors: 0 tournamentSize: 10 probMutation: 0.1 probCrossover: 0.9 numIters: 100 Accuracy: 96.84 Error Rate: 3.16 Not Classified: 0.00 Total time: 5.367 popSize: 1000 numSurvivors: 0 tournamentSize: 10 probMutatio...
<p>Here is a method for wrangling your data into a dataframe using <code>itertools.groupby()</code> and <code>pandas</code>:</p> <pre><code>from itertools import groupby import pandas as pd with open('test.txt', 'r') as f: chunks = [list(group) for k, group in groupby(f.readlines(), lambda x: x=='\n') if not k] ...
python|pandas|dataframe
1
373,390
53,694,679
Training discriminator and generator at the same time(Tensorflow)
<p>Usually in GAN codes using TensorFlow, we have the following form:</p> <pre><code> _, D_loss_curr, _ = sess.run( [D_solver, D_loss, clip_D], feed_dict={X: X_mb, z: sample_z(mb_size, z_dim)} ) _, G_loss_curr = sess.run( [G_solver, G_loss], feed_dict={z: sample_z(mb_s...
<p>The discriminator D and the generator G will not be trained in parallel when passing the list <code>[D_solver, D_loss, clip_D, G_solver, G_loss]</code> to function <code>sess.run()</code>. All operations of this list will be executed, but the function <code>Session.run()</code> cannot guarantee any order of executio...
tensorflow|machine-learning|neural-network|generative-adversarial-network
0
373,391
53,643,927
How to split a string into array of six character?
<p>I have a string that is :</p> <pre><code>doc = 'a3fprma3j4kfa3bedv' </code></pre> <p>And I want to create an array:</p> <pre><code>['a3fprm', 'a3j4kf', 'a3bedv'] </code></pre> <p>Every six character to be a string in an array When I try :</p> <pre><code>rer = [doc[i] for i in range(len(doc))] god = [] for i in...
<p>Try something like below. The only thing is the string has to be a multiple of 6 to display a value in the list. For example if you add 5 more characters to the string the output would be the same as the last 5 characters would be ignored.</p> <p>The difference from your code is the addition of a third parameter in...
string|python-3.x|numpy|split
2
373,392
53,763,021
Keras masking layer as input to lstm layer
<p>I'm trying to create a LSTM model. Before passing the data to the first LSTM layer, I want to add a <code>Masking</code> layer. I am able to do this using Sequential approach in Keras. See <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/Masking" rel="nofollow noreferrer">example</a>. However when...
<p>You have forgotten to create an input layer. First define the input layer and then pass the placeholder tensor to the Masking layer:</p> <pre><code>inp = Input(shape=(window_len, n_features)) masking = keras.layers.Masking(mask_value=0.0)(inp) lstm_h1 = keras.layers.LSTM(lstm_neurons)(masking) </code></pre> <p>And...
python|tensorflow|keras|lstm|rnn
4
373,393
53,551,975
How to know what Tensorflow actually "see"?
<p>I'm using cnn built by keras(tensorflow) to do visual recognition. I wonder if there is a way to know what my own tensorflow model "see". Google had a news showing the cat face in the AI brain.</p> <p><a href="https://www.smithsonianmag.com/innovation/one-step-closer-to-a-brain-79159265/" rel="nofollow noreferrer">...
<p>We have to distinguish between what Tensorflow <a href="https://towardsdatascience.com/applied-deep-learning-part-4-convolutional-neural-networks-584bc134c1e2" rel="nofollow noreferrer">actually see</a>:</p> <blockquote> <p>As we go deeper into the network, the feature maps look less like the original image and...
tensorflow|keras
1
373,394
53,758,842
Pandas How to resample column with strings
<p>I have a dataframe with: date;name The point is if I do a resample using something like:</p> <pre><code>df.set_index('date').resample('D')[&quot;name&quot;].sum() </code></pre> <p>The result concatenates all names from the resampling in one cell without separator. I want to be able to count name occurrences and plot...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.window.Rolling.count.html" rel="nofollow noreferrer"><code>Rolling.count</code></a>:</p> <pre><code>s = df.set_index('date').resample('D')["name"].count() </code></pre>
python|pandas|resampling
1
373,395
53,735,091
Trouble reading NCES IPEDS csv file with pandas
<p>ran into a trouble downloading and reading csv files provided by US Department of Education National Center for Education Statistics. Below is code that should run for folks that might be interested in helping me troubleshoot.</p> <pre><code>import requests, zipfile, io # First example shows that the code can work...
<p>Only took 7 months... Figured my answer. Wasn't rocket science.</p> <pre><code>csv_2006_df = pd.read_csv('hd2006_data_stata.csv', encoding='ISO-8859-1') </code></pre>
pandas|csv|unicode
0
373,396
53,442,288
urllib.error.HTTPError: HTTP Error 503: Service Unavailable python
<p>I used to access csv file from the following links for years.</p> <p><a href="http://www.football-data.co.uk/mmz4281/1819/E0.csv" rel="nofollow noreferrer">http://www.football-data.co.uk/mmz4281/1819/E0.csv</a></p> <p>It was,first of all, open source. I used to read it and convert it to data frame using Pandas</p>...
<p>I faced the same issue. It is due to network. In my office Anaconda/Jupiter notebook can't connect to internet however I am able to open the link in browser. Not sure whats your condition. If you are in office network. Try making your mobile as hotspot, come out of office network and then try.</p>
python|pandas|http-error
1
373,397
53,746,994
pandas apply with numpy interp, dimension problems
<p>I want to interpolate measurements made at a dynamic sets of frequencies into a fixed set of frequencies. I use Python 3.7 with pandas.apply and numpy.interp:</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame({'m1':[2.,3.], 'm2':[4.,6.], 'm3':[2.,3.], ...
<p>The issue is you are trying to return an array, which doesn't reduce. You can instead return a list of the values.</p> <pre><code>def myfunction(x): newfreqs = freqs*x[-1] result = np.interp(freqs, newfreqs, x[:-1]) return [*result] df.apply(myfunction, axis=1, raw=True) #0 [2.0, 3.6363636363636367,...
python|pandas|numpy|interpolation|apply
1
373,398
53,709,406
pytorch batch normalization in distributed train
<p>wondering how distributed pytorch handle batch norm, when I add a batch norm layer, will pytorch engine use the same allreduce call to sync the data cross node? or the batch norm only happen on local node.</p>
<p>Similarly to <a href="https://pytorch.org/docs/master/nn.html#torch.nn.DataParallel" rel="nofollow noreferrer">DataParallel</a> (check the first <em>Warning</em> box). It will compute the norm separately for each node (or, more precisely, each GPU). It will not sync the rolling estimates of the norm either, but it w...
pytorch
1
373,399
53,769,948
How to change a Pytorch CNN to take color images instead of black and white?
<p><a href="https://github.com/harveyslash/Facial-Similarity-with-Siamese-Networks-in-Pytorch/blob/master/Siamese-networks-medium.ipynb" rel="nofollow noreferrer">This code</a> I found has a neural net that is setup to take black and white images. (It's a siamese network but that part's not relevant). When I change it ...
<p>The error seems to be in fully connected part below:</p> <pre><code>self.fc1 = nn.Sequential( nn.Linear(8*100*100, 500), nn.ReLU(inplace=True), nn.Linear(500, 500), nn.ReLU(inplace=True), nn.Linear(500, 5)) </code></pre> <p>It seems the output of cnn is of shape<code>[8,30...
python|image|conv-neural-network|pytorch
1