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
368,500
18,713,929
Subsample pandas dataframe
<p>I have a <code>DataFrame</code> loaded from a <code>.tsv</code> file. I wanted to generate some exploratory plots. The problem is that the data set is large (~1 million rows), so there are too many points on the plot to see a trend. Plus, it is taking a while to plot.</p> <p>I wanted to sub-sample 10000 randomly di...
<p>You can select random elements from the index with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.choice.html" rel="nofollow noreferrer"><code>np.random.choice</code></a>. Eg to select 5 random rows:</p> <pre><code>df = pd.DataFrame(np.random.rand(10)) df.loc[np.random.choice(df.index, 5,...
python|numpy|pandas|subsampling
18
368,501
18,453,442
Comparing pandas Series for equality when they contain nan?
<p>My application needs to compare Series instances that sometimes contain nans. That causes ordinary comparison using <code>==</code> to fail, since <code>nan != nan</code>:</p> <pre><code>import numpy as np from pandas import Series s1 = Series([1,np.nan]) s2 = Series([1,np.nan]) &gt;&gt;&gt; (Series([1, nan]) == S...
<p>How about this. First check the NaNs are in the same place (using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isnull.html" rel="noreferrer">isnull</a>):</p> <pre><code>In [11]: s1.isnull() Out[11]: 0 False 1 True dtype: bool In [12]: s1.isnull() == s2.isnull() Out[12]: 0 ...
python|pandas|numpy|nan|equality-operator
9
368,502
61,795,914
Accessing last value in a time series dataframe with pandas and plotly
<p>How would I grab the very last value of a time series?</p> <p>I have a df with timeseries info for many countries, that tracks several variables and does some simple averaging etc.</p> <p>I just want to grab the most recent value / values for each country and graph it with plotly. I have tried using .last() but no...
<p>IIUC you need to filter your dataframe before hand : </p> <pre><code>dates = pd.date_range(pd.Timestamp('today'),pd.Timestamp('today') + pd.DateOffset(days=5)) df = pd.DataFrame({'Date' : dates, 'ID' : ['A','A','A','B','B','B']}) df2 = df.loc[df.groupby(['ID'])['Date'].idxmax()] print(df2) ...
python|pandas|dataframe|plotly
1
368,503
61,757,779
Does 'pandas' replace function have a problem handling large dictionary objects?
<p>I have a CSV file with over 50k rows and wanted to replace the values of a datetime column with just the date. The original value has the format "01-Jun-2015 00:00:00", so I made the following code:</p> <pre><code>import pandas as pd filepath = "my/file/path.csv" csv_file = pd.read_csv(filepath) datetimes = csv_fil...
<p>This should work:</p> <pre><code>csv_file['Date'] = csv_file['Date'].apply(lambda dt: dt.split()[0]) </code></pre>
python|pandas
0
368,504
61,697,043
I have imported an excel file into Jupyter, columns are stacked
<p>I imported the excel file, but for some reason the columns are not displayed horizontally. The ones displayed below have their own indexes. How can I rectify this?</p> <p>Thanks.</p> <p><a href="https://i.stack.imgur.com/DeAat.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DeAat.png" alt="enter...
<p>Change <code>print(energy)</code> to <code>display(energy)</code> </p>
python|excel|pandas|import
1
368,505
61,973,915
Fastest way in numpy to check if vectors are aligned or have opposite direction (truncated SVD post processing)
<p>I have a bunch of vectors that are stored in the columns of a matrix U. I have also a matrix V containing column vectors. Each vector in V can either be</p> <ul> <li>almost identical to its counterpart in U, with numerical approximations</li> <li>or have an opposite sign, with numerical approximations.</li> </ul> ...
<p>We can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.einsum.html" rel="nofollow noreferrer"><code>np.einsum</code></a> -</p> <pre><code>diag_VtU = np.einsum('ji,ij-&gt;j',Vt[:n_components, :], U[:, :n_components]) </code></pre> <p>Alternatively, with <code>np.matmul/@-operator</code> to get <...
python|numpy|vector|svd|eigenvalue
3
368,506
61,854,333
Convert from .npy to MLMultiArray for CoreML prediction in swift
<p>I have exported a PyTorch model to CoreML and want to do inference in swift. I have my input data stored on disk as a 2D float32 numpy ndarray <code>.npy</code> and need load into a <code>MLMultiArray</code> in swift. Is there a convenient way to do this? </p>
<p>Instead of saving as .npy (which is pickled), save the raw data from NumPy:</p> <pre><code>array.astype(np.float32).tofile(filename) </code></pre> <p>Now you can simply load this into a Data object in Swift and copy that into the MLMultiArray.</p>
swift|numpy|pytorch|coreml
4
368,507
61,849,215
How is it possible that updating a numpy array derived from a Pandas DatFrame column also (unexpectedly) updates the data frame column?
<p>Stumbled across this oddity while debugging, updating a numpy array derived from a Pandas Dataframe column also unexpectedly modifies the values of the Dataframe, although it was never referenced in the update, only the numpy array is mentioned. How is this possible?</p> <pre><code> import numpy as np impor...
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.values.html" rel="nofollow noreferrer"><code>pandas.DataFrame.values</code></a> returns a view of the data (rather than a copy) if the columns are all of the same type. Since you only have one column, you actually have a reference t...
python|pandas|numpy
1
368,508
61,820,329
how can i delete specified words that occur in list
<p>I have a data-frame that has text in the first column named 'original_column'.<br /><br /> I have successfully been able to pick specific words out of the text column 'original_column' with a list and have them appended to another column and deleted from the original column with the following code:</p> <pre><code>l...
<p>Let us do <code>replace</code> </p> <pre><code>df['original column']=df['original column'].replace(regex=r'(?i)'+ df['list1'],value="") df Out[101]: original column list1 0 text text word 1 text text and </code></pre>
python|pandas|list|dataframe|split
1
368,509
61,894,724
How to create a bigger matrix from a smaller one according to a rule
<p>I have a matrix, say 3 x 3</p> <pre><code>x= np.arange(0,9,1).reshape((3,3)) </code></pre> <p>and I want to get a bigger matrix (9x9) built according to the following simple rule:</p> <p>the first three rows of the new matrix are identical, and made from the first row of x and zeros to the end.</p> <p>The second...
<p>You can use <a href="https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.linalg.block_diag.html" rel="nofollow noreferrer">block_diag</a> from scipy.linalg.</p> <pre><code>""" &gt;&gt;&gt; print(answer) [[0 1 2 0 0 0 0 0 0] [0 1 2 0 0 0 0 0 0] [0 1 2 0 0 0 0 0 0] [0 0 0 3 4 5 0 0 0] [0 0 0 3 4 5 0...
python|numpy|matrix
2
368,510
61,709,395
Numpy operator for each vector element with matrix individual row multiplication
<p>Is there a numpy operator that will result in the individual vector element multiplying with the corresponding matrix row?</p> <p>For e.g.,</p> <pre class="lang-py prettyprint-override"><code> import numpy a,b=numpy.array([1,2]), numpy.array([[1,2,3,4],[5,6,7,8]]) </code></pre> <p>When I multiply a and b,...
<p>You can use: </p> <pre><code>a[:,None]*b </code></pre> <p>This should be fairly fast with no extra calculation cost.</p> <p>output:</p> <pre><code>[[ 1 2 3 4] [10 12 14 16]] </code></pre>
python|numpy|sparse-matrix|matrix-multiplication
1
368,511
61,775,835
How to add a calculated column in a pandas dataframe?
<p>I am new to python/pandas so I'm struggling a bit here. I have a dataframe with air quality data from 2016 to 2020. I want to calculate the annual rate of change for each measured value to compare them with the value the year before at the same day and month.</p> <p>These are the first lines of the dataframe.</p> ...
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pct_change.html?highlight=pct_change#pandas.DataFrame.pct_change" rel="nofollow noreferrer">pandas.DataFrame.pct_change</a>You can easily retrieve it using the 'pandas:pct_change' method.</p> <pre><code>data=''' Date Country City S...
python|pandas
0
368,512
61,920,759
Insert 15 min datetime in hourly intervals
<p>I have a dataframe with 3 columns of which the first column is a datetime.</p> <p>It looks like this</p> <pre><code>Datetime Level1 Level2 2016-02-24 01:00 12 15 2016-02-24 02:00 14 13 2016-02-24 03:00 8 12 </code></pre> <p>Now I would like to add 15 min interval values be...
<p>Set the datetime as index (after converting to datetime), and use the asfreq method, with a forward fill, to fill the null values with previous values :</p> <pre><code>#thanks to @a_guest for the cleaned sample data df = pd.DataFrame( data=[['2016-02-24 01:00', 12, 15], ['2016-02-24 02:00', 14, 13], ...
python|pandas|datetime
2
368,513
62,033,323
How can I remove a line from a csv file using pandas?
<p>I'm trying to be able to delete specific lines from a csv file using the pandas. This is what I have so far:</p> <pre><code>def delete_from_file(): student_name = input("What is the name of the student? ") df = pd.read_csv('students.csv', names = ['name', 'phone number', 'class time', 'duration'], index_col...
<p>Change your function to </p> <pre><code>def delete_from_file(student_name): df = pd.read_csv('students.csv', names = ['name', 'phone number', 'class time', 'duration']).set_index('name') df=df.drop(student_name) return df </code></pre>
python|pandas
0
368,514
61,648,869
can we concatenate more then two data to one tensor
<p>I have three numpy array that contains my data.</p> <pre><code>X_train = np.zeros((1, 288, 288, 3), dtype=np.uint8) X_train2 = np.zeros((1, 288, 288, 3), dtype=np.uint8) X_train3 = np.zeros((1, 288, 288, 3), dtype=np.uint8) </code></pre> <p>Using np.concatenate I can concatenate two image to one tensor as below ...
<p>Yes. You can concatenate as many numpy array as you want.</p> <pre><code>X_train_final = np.concatenate([X_train, X_train2, X_train3], axis = -1) </code></pre> <p>is valid and will give you an array where, the last dimension will be 3 times as in the original array. You can continue this way for as many arrays as ...
python|numpy|tensorflow|keras
1
368,515
61,879,166
Pandas groupby month and year (date as datetime64[ns]) and summarized by count
<p>I have a data frame, which I created in pandas, grouping by date and summarizing by rides. </p> <pre><code> date rides 0 2019-01-01 247279 1 2019-01-02 585996 2 2019-01-03 660631 3 2019-01-04 662011 4 2019-01-05 440848 .. ... ... 451 2020-03-27 218499 452 2020-03-28 143305 453 20...
<p>you can <code>groupby</code> and get the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.year.html" rel="noreferrer">dt.year</a> and the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.month_name.html" rel="noreferrer">dt.month_name</a> from t...
python|pandas|pandas-groupby|python-datetime
7
368,516
61,898,670
How to compute the means of data separated by dashes with pandas
<p>I am trying to clean csv files so I retrieved all values which contained dashes in my ages column and I have this output </p> <pre><code>504 40-49 756 20-29 758 40-89 </code></pre> <ul> <li>I would like to have the age mean instead of recording the age range as start_age-end_age.</li> <li>I tried...
<ul> <li>To create the desired output, add <code>age_mean</code> and drop <code>age_range</code>.</li> <li><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html" rel="nofollow noreferrer"><code>pandas.Series.str.split</code></a></li> <li><a href="https://pandas.pydata.org/pand...
python|python-3.x|pandas|csv|data-cleaning
3
368,517
61,782,281
Rearrange 3D array in python
<p>I have big binary 3D data and I want to re-arrange the data such as it is a sequence of values in order achieved by parsing the original data as sub-arrays of size (4x4x4).</p> <p>For example, if the data is 2D and I want to re-arrange the data from 2x2 sub-arrays <a href="https://i.stack.imgur.com/k10VZ.png" rel="...
<pre><code>x,y,z = 1200,800,400 data = np.empty([x,y,z]) # numpy calculates the shape of -1 out = data.reshape(-1, 4, 4, 4) out.shape &gt;&gt;&gt; (6000000, 4, 4, 4) </code></pre>
python|numpy|scipy
0
368,518
61,872,127
Assign values to with condition in a pandas dataframe?
<p>I have a pandas dataframe that looks like the following</p> <pre><code>df time case1 case2 case3 0 5 house bank atm 1 3 bank house pharmacy 2 10 bank bank atm 3 20 house pharmacy house </code></pre> <p>I want to add a column for each case that corresponds...
<p>You're probably better off defining a dictionary, and use the actual values to lookup:</p> <pre><code>from operator import itemgetter d = {'house':[20, 10], 'bank':[5, 1], 'atm':[3,1], 'pharmacy':[10,5]} l = list(zip(*(itemgetter(*l)(d) for l in df.loc[:,'case1':].values))) for ix,col in enumerate(['p1','p2','p3...
python|pandas
2
368,519
61,902,753
How do I create a 2D-array from calculation of a formula using two arrays as input?
<p>I am trying to calculate how many hours of sunlight each latitude of Earth receives every year. I have a formula which calculates this, that uses two arrays as input, the day of the year, and the latitude. What I want to do is to use the formula to create a 2D-array with each day on one axis and each latitude on ano...
<p>Try <a href="https://numpy.org/doc/1.18/reference/generated/numpy.meshgrid.html" rel="nofollow noreferrer">numpy.meshgrid</a>. This will create two 2D-arrays for latitude and days for you:</p> <pre><code>lat2d, days2d = np.meshgrid(Latitude, Days) </code></pre> <p>Those arrays will have shape <code>(365, 90)</code...
python|arrays|function|numpy|matrix
1
368,520
61,970,310
In Pandas can we select columns by names and by regex?
<p>Let's say my Pandas data frame was as follows:</p> <pre><code>import pandas as pd df = pd.DataFrame( dict(ID = [1, 2, 3], xz = [0, 1, 1], yz = [4, 5, 6], yx = [7, 11, 18], xy = [10, 10, 11]) ) </code></pre> <p>If I want to select all those columns whose names contain an <co...
<p>You can match on both conditions separating with a <code>|</code>, which acts like an <code>or</code> for pattern matching. If you want to match exact column names, you'll need to add the beginning and end of strings too:</p> <pre><code>df.filter(regex = r'x|^ID$', axis=1) ID xz yx xy 0 1 0 7 10 1 2...
python|pandas
3
368,521
61,975,232
Can I use regular expressions search or match on a Python Pandas column where each cell is a list of lists?
<p>I have a somewhat large CSV file (>2,000 rows) I've read into Pandas and want to create a new indicator column based on whether or not a specific word appears in one of the data columns. I have been trying to use regex search, which may be overkill because the word will always appear split by spaces, but the cells o...
<p>Instead of running a for loop (which is slow) you can use <code>map</code>. You can convert the list to <code>str</code> for calling the regex. Like this:-</p> <pre><code>import pandas as pd import numpy as np import re cycling = pd.DataFrame( { 'qty' : [1,0,2,1,1], 'item' : ['frame','frame',np...
python|regex|pandas|flatten|dummy-variable
0
368,522
61,767,981
Session Crashed in Google Colab at the begining of first epoch in TimeDistributed CNN model
<p>I'm working with video classification of 5 classes and using <strong>TimeDistributed CNN</strong> model in <strong>Google Colab</strong> platform. The train dataset contains <strong>80</strong> videos containing <strong>75 frames</strong> each. The validation dataset contains <strong>20</strong> videos containing <s...
<p>You could try a tensorflow's Dataset module. For example, instead of passing a array of images, you pass a list of image path's, the dataset generator at the time of training will only partially load 1 batch of images at a time. This way you won't overwhelm the memory. Here's an example</p> <pre><code>def preprocess...
python|tensorflow|keras|google-colaboratory
0
368,523
61,672,096
Numpy: manipulate elements depending on the value without looping over the entire array
<p>I have a numpy array x and I would like to perform an action on the elements of x depending on its value. For example suppose I want to take the square for all negative elements and take the fourth power for all the other elements. The following code does the trick</p> <pre><code>import numpy as np x = np.array([-2...
<p>generically</p> <pre><code>mask = x&lt;0 y[mask] = fn1(x[mask]) mask =~mask y[mask] = fn2(x[mask]) </code></pre> <p>The mask test and the fn are written to work with arrays.</p>
numpy|if-statement|boolean
1
368,524
61,931,489
apply numpy functions array to an array of elements
<p>I am trying to get a an array generated from applying differnt functions all stored in a numpy array on the same parameter, is there an efficient way coding this using numpy?</p> <pre><code> #func_array- a numpy array of different functions that get the same parameter #X - parameter for evey function in func...
<p>I once had the exact same questions, and this is what I was told:<br> The vectorization speed-up that numpy array operations provide is due to the base data-types defined for the array (say an <em>array of floats</em>, for instance).<br> When the array elements are objects, this advantage is mostly nullified. Since ...
python|arrays|numpy
0
368,525
61,790,683
Dropna with only one nan value in the df
<p>I am searching and selecting values in a data frame in iteration and it happens that in a selection I may have only one row with a Nan value and I do not seem to be able to get rid of if. Used dropna and id didn't seem to do the trick.</p> <p><code>df2=df1.dropna(subset=['x'])</code></p> <p>I printed out other val...
<p>Assume that your DataFrame contains <em>NaN</em> in <strong>other</strong> column than <em>x</em>, something like:</p> <pre><code> x y z 0 10.0 20.0 30.0 1 11.0 22.0 33.0 2 40.5 NaN 80.4 3 60.5 80.2 90.4 </code></pre> <p>Then <code>df1.dropna(subset=['x'])</code> is not likely to drop any...
pandas
0
368,526
61,840,652
Backpropagation bug
<p>I am trying to implement backpropagation from scratch. While my cost is decreasing, gradient check yields a whooping <code>0.767399376130221</code>. I've been trying to figure out what's wrong and managed to slim down the code to these few lines: </p> <pre><code> def forward(self,X,y): z2 = self.params_l1.dot(...
<p>I managed to get a difference of <code>1.7250119005319425e-10</code> by computing <code>delta3</code> just through <code>yh - y</code>and no further multiplications. Now I need to figure out why this is. </p>
python|numpy|machine-learning|backpropagation
0
368,527
61,933,436
2D Dataframe to a CSV
<p>I have a dataframe in below shape.</p> <pre><code> M1 M2 M3 Cus1 11 1 2 Cus2 4 76 45 Cus3 4 8 6 </code></pre> <p>I need to export this as csv to another file.And there after my intention is to use visualization software like (PowerBi,Cognos analytics) and make some graphs. How to export...
<p>This should do the job</p> <pre><code> df.to_csv('csv_filename.csv') </code></pre> <p>or,</p> <pre><code>df.to_csv('&lt;path_to_csv_file&gt;/csv_filename.csv') </code></pre>
python|pandas
1
368,528
61,724,210
Python Pandas: plot values against hour and date
<p>I have a Panda Dataframe <em>prices</em> with the following structure:</p> <pre><code>prices Out[28]: FCR-N FCR-D Period 2016-01-01 00:00:00 28.949 5.285 2016-01-01 01:00:00 28.820 5.314 2016-01-01 02:00:00 28.734 5.330 2016-01-01 03:00:00 28.822 5.2...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot_table.html" rel="nofollow noreferrer"><code>DataFrame.pivot_table</code></a> with some aggregation funecion, e.g. <code>sum</code> and then <a href="https://seaborn.pydata.org/generated/seaborn.heatmap.html" rel="nofollow n...
python|pandas
1
368,529
61,797,463
Groupby and create a new column by randomly assign multiple strings into it in Pandas
<p>Let's say I have students infos <code>id</code>, <code>age</code> and <code>class</code> as follows:</p> <pre><code> id age class 0 1 23 a 1 2 24 a 2 3 25 b 3 4 22 b 4 5 16 c 5 6 16 d </code></pre> <p>I want to groupby <code>class</code> and create a new column named <...
<p>Use <a href="https://numpy.org/doc/stable/reference/random/generated/numpy.random.choice.html?highlight=choice#numpy.random.choice" rel="nofollow noreferrer"><code>numpy.random.choice</code></a> with number of values by length of <code>DataFrame</code>:</p> <pre><code>df['major'] = np.random.choice(['math', 'art', ...
python-3.x|pandas
2
368,530
61,933,895
Pandas DataFrame returning a Tuple, but cannot access individual numbers?
<p>I have a very simple DataFrame </p> <p><a href="https://i.stack.imgur.com/NF328.png" rel="nofollow noreferrer">DataFrame</a></p> <pre><code>import pandas as pd data = pd.read_excel('HSH_Data.xlsx') config = 'A1A2-Car-SiC' seal_size = 2125 p1 = (data.loc[(data.Configuration == config) &amp; (data.Seal == seal_si...
<p>Just look at <code>p1.D2.values[0]</code> or <code>p1.L2.values[0]</code>.</p>
python|pandas|tuples
0
368,531
61,849,855
Passing function name as string + Panda Dataframe + Azure Databricks
<p>I got a function called 'changeUpper', i want call this function on a given column of Pandas DataFrame based on Metadata definitions.</p> <p><strong><em>Example</em></strong> in Metadata I record to call function <code>changeUpper</code> on <code>PrimaryColumn</code> (this holds name of the Column).</p> <p>I wante...
<p>I got this working as :</p> <pre><code>for index, row in rulesPandas.iterrows(): func = eval(row['FunctionName']) newcolumn = row['NewColumnName'] if(newcolumn is not None): sourcePandas = sourcePandas.assign(**{f'{newcolumn}': sourcePandas[row['PrimaryColumn']].apply(func)}) else: sour...
python|pandas|dataframe|databricks
1
368,532
61,777,109
deleting the name of the columnns and keep the rest of the column
<p>I have a dataframe that is like this:</p> <pre><code> Code 345162 346199 347607 354144 355542 357052 357358 358632 361794 362237 Date 2018-06-27 49.0 59.0 47.0 56.0 15.0 84.0 44.0 0.0 0.0 0.0 2018-06-28 42.0 75.0 44.0 46.0 90.0 ...
<p>Here try this</p> <pre><code> df.rename(columns={'Code':" "},inplace=True) Code 345162 346199 347607 354144 355542 357052 357358 358632 361794 362237 Date 2018-06-27 49.0 59.0 47.0 56.0 15.0 84.0 44.0 0.0 0.0 0.0 2018-06-28 42.0 75.0 4...
python|pandas|dataframe
0
368,533
61,837,247
find a matching string in columns in python pandas
<p>I have a data in the following order</p> <pre><code>Movie_title views likes genres actor_name director_name xxc - - 455 - ... Action ... ... nnj - - - Funny hhs - - - news jjs - - - Action uus - - - ... y...
<p>As Ch3steR already said to you in comments, your filter is done by checking df.genres == "action".</p> <p>You can do before that something like</p> <pre><code>columns = ["movie", "genre"] df = df[columns] </code></pre> <p>Which will result in a df made by these two columns (or more if added), after that you can s...
python|pandas
0
368,534
61,833,866
Duplicate rows based on value with condition
<p>I need to replicate some rows in a panda data frame like this</p> <pre><code>name times A 2 B 1 C 3 D 20 ... </code></pre> <p>What I need is to replicate rows just when col2 value is less than 20</p> <p>What I'm doing now is:</p> <pre><code>for t in df["times"]: if t &lt; 2...
<p>Use:</p> <pre><code>#condition lt for &lt; mask = df['times'].lt(20) #filter by boolean indexing df1 = df[mask].copy() #repeat rows df1 = df1.loc[df1.index.repeat(df1['times'])] #add rows higher like 20, sorting and create default index df = pd.concat([df1, df[~mask]]).sort_index().reset_index(drop=True) print (df...
python|pandas|dataframe|duplicates
4
368,535
61,649,736
How can I use the loc function with condition on Pandas Series?
<p>so I have a Series looks like this:</p> <pre><code>0 0 1 13 2 100 3 500 </code></pre> <p>And I want to return all the numbers that are bigger than 10.</p> <pre><code>1 13 2 100 3 500 </code></pre> <p>And I thought using the .loc function but I could not without the column name. I do not want to convert it to dat...
<pre><code>x=pd.Series([0,13,100,500]) x=x[x&gt;10] </code></pre>
python|pandas|series
3
368,536
61,752,658
Multiply a scalar to a tensor with tensorflow keras backend
<p>I'm going to use a sawtooth activation function in one layer and have defined it like this: (the form of sawtooth function is not the important part and it is this function of x for a sum over many terms: <code>sin(x) - 1⁄2sin(2x) + 1⁄3sin(3x) - 1⁄4sin(4x) + 1⁄5sin(5x) - 1⁄6sin(6x) + ...</code> , I've used 500 te...
<p>Providing the solution here (Answer Section), even though it is present in the Comment Section, for the benefit of the community.</p> <p>After adding <code>I = I[:, None]</code> to <code>sawtooth1</code> function has resolved the issue.</p> <p>Here is the updated code </p> <pre><code>def sawtooth1 (x): I= K.a...
python|tensorflow|keras
0
368,537
61,757,170
Python: Unstacked DataFrame is too big, causing int32 overflow
<p>I have a big dataset and when I try to run this code I get a memory error.</p> <pre><code>user_by_movie = user_items.groupby(['user_id', 'movie_id'])['rating'].max().unstack() </code></pre> <p>here is the error:</p> <pre><code>ValueError: Unstacked DataFrame is too big, causing int32 overflow </code></pre> <p>I ...
<p>According to Google, you can downgrade your pandas version to 0.21 which has no problem with pivot table and too big data.</p>
python|pandas|data-science|data-analysis
2
368,538
61,940,416
Python: Evaluating multivariate normal distribution at the same point but different means and standard deviations
<p>I tried using <code>scipy.stats.multivariate_normal()</code> to evaluate the pdf at a point x for different values of the mean and of the standard deviation. However, it doesn't broadcast.</p> <h3>Minimal Working Example</h3> <pre><code>import numpy as np from scipy import stats # A single x where I want to evalu...
<p>The question title says "multivariate normal", but the code shows a univariate input for <code>x</code>, and in a comment you say "... I want to evaluate a large number of univariate normal distributions...".</p> <p>To evaluate different univariate normal distributions at a single point, use <code>scipy.stats.norm...
python|numpy|scipy
3
368,539
61,625,801
Division between two dataframes using column value
<p>{In [16]: print(data_15)</p> <pre><code> ene2015 feb2015 mar2015 abr2015 may2015 jun2015 ... c12015 c22015 c32015 s12015 s22015 a2015 statename ... Nacional 38.0 32.0 45.0 49.0 35.0 36.0 ... 164.0 131.0 12...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.join.html" rel="nofollow noreferrer"><code>DataFrame.join</code></a> for add <code>pob_15</code> and then divide by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.div.html" rel="nofollow noref...
python|pandas
0
368,540
62,039,682
How to quickly convert a pandas dataframe to a list of tuples
<p>I have a pandas dataframe as follows.</p> <pre><code>thi 0.969378 text 0.969378 is 0.969378 anoth 0.699030 your 0.497120 first 0.497120 book 0.497120 third 0.445149 the 0.445149 for 0.445149 analysi 0.445149 </code></pre> <p>I want to convert it to a...
<p>Use <code>zip</code> by index with map tuples to lists:</p> <pre><code>a = list(map(list,zip(top_words.index,top_words))) </code></pre> <p>Or convert index to column, convert to nupy array and then to lists:</p> <pre><code>a = top_words.reset_index().to_numpy().tolist() </code></pre> <hr> <pre><code>print (a) [...
pandas
1
368,541
62,040,586
Numpy complaining about ambigoous array: ValueError: The truth value of
<p>I have a minimal code in Python 3, which uses numpy and the function <code>apply_along_axis</code>. I cannot understand the reason I am having this error:</p> <pre><code>ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() </code></pre> <p>Providing a direct formu...
<p>Look at what <code>apply_along_axis</code> passes to your function:</p> <pre><code>In [99]: def foo(x): ...: print(x) ...: return x ...: In [100]: np.apply_along_axis(foo, -1, p) ...
arrays|python-3.x|numpy
3
368,542
61,731,278
How to extract and separate random tuple values from a Python dataframe?
<p>Two values, say subject and subject category exist as columns in a data frame. Along with this I have the weight of subject in another column. I wish to create another data-frame that has random instances of a subject and it’s corresponding subject category based on the weights of the subject. The tricky part here...
<p>Pandas has rich API, with many methods available for common data processing tasks. You should use these methods where available, because they're thoughtfully designed, robust, and well tested.</p> <p>Here, you should use the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sample...
python|pandas|dataframe|random|tuples
0
368,543
61,948,103
Conditional merge / join of two large Pandas DataFrames with duplicated keys based on values of multiple columns - Python
<p>I come from R and honestly, this is the simplest thing to do in one line using R data.tables, and the operation is also quite fast for large datatables. Bu I'm really struggling implementing it in Python. None of the use cases previous mentioned were suitable for my application. The major issue at hand is the memory...
<p>Yeah. It's an annoying problem. I handled this by splitting the left DataFrame into chunks.</p> <pre class="lang-py prettyprint-override"><code>def merge_by_chunks(left, right, condition=None, **kwargs): chunk_size = 1000 merged_chunks = [] for chunk_start in range(0, len(left), chunk_size): p...
python|pandas|merge|conditional-statements|large-data
1
368,544
61,638,143
How to groupby a dictionary and aggregate a pandas dataframe
<p>I have a dataframe 'df' with index 'Country' and a column 'Estimated Population'. <a href="https://i.stack.imgur.com/r4P1E.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/r4P1E.png" alt="enter image description here"></a></p> <p>The index has 15 country names. I also have a dictionary:</p> <pre>...
<p>You need to change the <strong>dtype</strong> of the <code>Estimated Population</code> column before applying the <code>.agg</code> function. </p> <p>Use:</p> <pre><code>df['Estimated Population'] = df['Estimated Population'].astype(float) </code></pre> <p>Or,</p> <pre><code>df['Estimated Population'] = pd.to_nu...
python|pandas
3
368,545
61,893,707
Pythonic way to find all the different intersections and differences between two lists of arrays
<p>This is the generalization of a <a href="https://stackoverflow.com/questions/61647198/pythonic-and-efficient-way-to-find-all-the-different-intersections-between-two-p">previous question</a> of mine. I need to find all the intersections and differences between two lists of different arrays. There are no intersections...
<p>There is no point to separate arguments, the result will be the same as you unite <code>x</code> and <code>y</code>. So you have set of sets and try to find separate pieces. To find them you can iterate through all elements and remember at which sets this value was encountered. Then if 2 elements have exactly the sa...
python|numpy|set|intersection|difference
1
368,546
61,883,791
Reading S3 files from a manifest and processing them in parallel using Pandas
<p>I have about 50k to read from S3 using a manifest file. I have to read contents of every single (JSON) file into a dataframe and process the files (normalize them as database tables). Right now I have a working code that take about 15hours to process the 50k files. I have to run this as a daily job. Is there any way...
<p>You use the <a href="https://docs.python.org/3.8/library/multiprocessing.html" rel="nofollow noreferrer">multiprocessing module</a> to download JSON files in parallel. You code contains 3 <em>for</em> blocks. You can do each one of them in parallel. An example of how to do this for the first <em>for</em> follows:</...
json|pandas|amazon-web-services|amazon-s3|boto3
1
368,547
61,974,719
How to handle a column which contains date , number, string values in Python Data Frame
<p>I have a Input CSV file in which column A has only number values and Column B contains Number , string and date . When i try to read this CSV file with pd.read_csv and write the data to excel file using to_excel() function ,the output excel file stores the Value of date, number as string values in column B (Note: I...
<p>As I could understand , multiple fomating on same column is the the requirement here.</p> <p>check if below lines work for you </p> <pre><code># this will change all possible values into int df['yourcolumn']= df['your column'].astype(int, errors='ignore') # this will convert all possible values in date df['yourcol...
python|pandas|numpy|xlwings
0
368,548
57,959,305
TensorFlow: How to combine rows of tensor with summing the 2nd element of tensor which has the same 1st element?
<p>For example, I want to <code>add</code> the 2nd element of this tensor where the 1st element is same. Any Numpy based solution is also welcomed! </p> <ul> <li>From :</li> </ul> <pre class="lang-py prettyprint-override"><code>x = tf.constant([ [1., 0.9], [2., 0.7], [1., 0.7], [3., 0.4], [4., 0.8...
<p>numpy solution:</p> <pre><code>x = np.array([ [1., 0.9], [2., 0.7], [1., 0.7], [3., 0.4], [4., 0.8]]) ans = np.array([[i,np.sum(x[np.where(x[:,0]==i), 1])] for i in set(x[:,0])]) </code></pre> <p>gives </p> <pre><code>array([[1. , 1.6], [2. , 0.7], [3. , 0.4], [4. , 0.8]]...
python|numpy|tensorflow
2
368,549
57,797,980
Sort multiindex pivot table pandas
<p>Would like to sort a pandas pivot by its values.</p> <pre><code>data = {'Counterparty': {0: 'A', 1: 'B', 2: 'B', 3: 'A', 4: 'A', 5: 'C', 6: 'D', 7: 'E', 8: 'E', 9: 'C', 10: 'F', 11: 'C', 12: 'C', 13: 'G'}, 'Contract': {0: 'A1', 1: 'B1', 2: 'B2', 3: 'A2', 4: 'A3', 5: 'C1', 6: '...
<p>First remove <code>fillna</code> for avoid mixed values numeric and strings and then sorting by tuples created from <code>MultiIndex</code>, not by <code>MultiIndex.columns.names</code>. Last if need <code>All</code> row to last row add <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat...
pandas|pivot-table
1
368,550
58,101,395
Using higher frequency data as a proxy for lower-frequency data
<p>I have two times series - annual and quarterly. Annual data ends in 2018, but quarterly data goes till 2019q3. What's the best way to combine the two, where Python checks what's the latest available quarterly and annual data and fills annual time series with the latest quarterly value?</p> <p>This is what I have in...
<p>You can organize your data to use a <code>DatetimeIndex</code>. The yearly frame is then fine (if there's one row per year) but for the quarter DataFrame we need to take the last value in each year, accomplished with <code>resample.last</code>. <code>combine_first</code> gives us priority to the yearly DataFrame whe...
python|pandas|time-series
0
368,551
57,743,599
Changes in pandas dataframe appearance
<p>I have a data frame, I need to change the look and feel of that dataframe to send that dataframe over email. I need to change the color of individual rows needs to make some rows bold in between the dataframe.</p> <p>Input DF:- </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data...
<p>I don't understand the structure of your data frame, however, applying a conditional styling is possible in pandas through <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html" rel="nofollow noreferrer"><code>pd.DataFrame.style</code></a> feature.</p> <p>I used a subset of you <code>DataFrame...
python|pandas|dataframe
0
368,552
57,847,007
Efficient row-wise operation (aggregation) based on column values
<p>I am working on a large dataset, and need to combine certain columns into a list. The challenge is, the number of columns chosen, is subject to another key value, which is different for every row.</p> <h2>Example:</h2> <h3>Original dataset:</h3> <pre><code>Key Col1 Col2 Col3 Col4 Col5 NonrelatedCols 1 a b ...
<p>Consider only the columns of importance:</p> <pre><code> Key Col1 Col2 Col3 Col4 Col5 0 1 a b c d e 1 3 r b x d c 2 2 k d q l w 3 0 w a c s w </code></pre> <p>Assuming <code>Key</code> is always in the first column, <code>apply</code> the <...
python|pandas|performance|numpy|dataframe
2
368,553
58,031,254
Pandas search and replace with dictionary
<p>I am trying to replace some keywords in pandas dataframe using dictionary, the data in column is a filepath, it should replace the keyword in the dictionary if it exists in filepath. </p> <pre><code>title_rename = {'ABCD':'LWD','MSC':'MWD', 'MRI':'MD' ,'TRI':'TXD'} all_files.replace({'Title':title_rename},inplace =...
<p>You can use pandas str:</p> <p><code>for k,v in title_rename.items(): all_files.Title = all_files.Title.str.replace(k,v)</code></p>
regex|pandas|replace
0
368,554
57,998,590
How to flatten a pandas column of nested dicts, into separate columns for each key
<p>I have a csv with 500+ rows where one column "_source" is stored as JSON. I want to extract that into a pandas dataframe. I need each key to be its own column.</p> <p>I have a 1mb JSON file of online social media data that I need to convert the dictionary and key values into their own separate columns. The social ...
<h2>Go to the <code>_source</code>:</h2> <h3><code>_source</code> to <code>list</code>:</h3> <ul> <li>Given the sample data from the question <ul> <li>create a <code>list</code> of all the rows in <code>_source</code></li> </ul></li> </ul> <p><a href="https://i.stack.imgur.com/4AkwS.png" rel="nofollow noreferrer"><...
python|json|pandas|dataframe|dictionary
3
368,555
57,913,754
Copy row of data from one pandas dataframe to another
<p>A pandas newbie here. I imported an excel data into pandas, I want to copy subset of data of a specific row (placeholder) from one dataframe (Error_data1) to another dataframe (Error_data2) where the 'placeholder' exists. </p> <p>Here is the first 4 rows of Error_data1 (it has 150 rows)</p> <pre><code>index stu...
<p>You can try merging the two dataframes on student names.</p> <pre class="lang-py prettyprint-override"><code> combined = Error_data1.merge(Error_data2, on='student', how='left').fillna(0) </code></pre>
python-3.x|pandas
1
368,556
57,896,199
numpy randomly sample from array where the values are not 0
<p>I am creating a numpy binary array with zeros and ones as follows:</p> <pre><code>import numpy as np x = np.zeros((10, 10, 10)) x[:4, :4, :4] = 1 x = x.ravel() np.random.shuffle(x) x.reshape(10, 10, 10) </code></pre> <p>Now what I want to do is randomly sample 20 positions within this array where the value is 1. i...
<p>You can get the coordinates with <code>np.where</code>. This will give you a 3-tuple with arrays for the indices where the position is <code>1</code>.</p> <p>We can use <code>np.transpose(..)</code> or <code>zip(..)</code> to generate 3-tuples with these, and then use for example <code>random.sample(..)</code> to s...
python|numpy
4
368,557
57,815,105
How to print the activation output of specified layers
<p>I am quite new to Keras and deep learning and I have been wanting to print outputs of a section of my layers (named <code>output[x]</code>)</p> <p>Down below you can find a section of the architecture. Do note that I have not provided any reproducible code.</p> <p>The goal is to validate the <code>val_loss</code> ...
<p>The thing is, when you define your graph like that, you don't have any values inside it. <code>output1</code> is just a placeholder. If you want to visualize/display/plot anything from your graph (or even inspect your computational graph), I would suggest you take a look at <a href="https://www.tensorflow.org/guide/...
python|tensorflow|keras|softmax|activation-function
0
368,558
58,059,685
Memory overflow during inference in tensorflow
<p>I have written these functions to carryout inference using the saved weights of a trained binary classifier. I have about 120k images to make inference. But the GPU freezes after getting to 82k images. Please is there anything I need to fix in my code to resolve this memory issue. Could the model be saving the check...
<p>I finally found a work around for this issue. I had to break <code>classify_and_collect_image_with_bags</code> into these 3 simpler functions:</p> <pre><code>def create_inference_dataset(image_paths): inference_dataset =tf.data.Dataset.from_tensor_slices(image_paths) inference_dataset = inference_dataset.m...
python-3.x|tensorflow|tf.keras
1
368,559
58,109,754
Drop row using time interval or threshold in pandas
<p>I am a beginner in python I have a <code>dataframe</code> which appears every second. My data looks like this</p> <pre><code> Time Id 0 9:00:00 A 1 9:00:30 B 2 9:00:50 C 3 9:01:03 D 4 9:01:25 E 5 9:02:04 F </code></pre> <p>Based on this post <a href="https://stackoverflow.com/questions/55559498/d...
<p>Use</p> <ul> <li><p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_timedelta.html" rel="nofollow noreferrer"><code>pd.to_timedelta</code></a> - Convert argument to timedelta.</p> </li> <li><p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Grouper.html" rel="...
python|pandas
2
368,560
57,895,583
Numpy where generating x,y coordinates that cause segmentation mask to be diagonally split
<p>Below is an image:</p> <p><img src="https://raw.githubusercontent.com/ebolotin6/ebolotin6.github.io/master/images/image1.png" alt="Original image"></p> <p>This is a segmentation mask of a class within this image:</p> <p><img src="https://raw.githubusercontent.com/ebolotin6/ebolotin6.github.io/master/images/image2...
<p>You do not have an issue. It works fine:</p> <blockquote> <p>poly = patches.Polygon(pts)</p> </blockquote> <p>A lovely, yet quite complex polygon... You expect it to plot the border, yet you pass all the coordinates of all the points in the region. You may want to try:</p> <blockquote> <p>poly = patches.Polyg...
python|numpy|matplotlib|object-detection|image-segmentation
1
368,561
58,059,254
Saving variables in Python as columns without brackets
<p>I have a code which returns some variables that I would like to later on use in another program. However, the output doesn't look like I want it to. The rows are within brackets [], and I would like to have them removed. </p> <p>I have found the following question that deals with something similar; however, I am sa...
<p>My suspicion is that <code>itemndsT</code> is a list type, which is why when you write it to the file it includes the square brackets. You'll need to format it into a string yourself before writing it. There are a few ways you can do this, but using <a href="https://docs.python.org/2/library/string.html#string.join"...
python|numpy|save
1
368,562
58,026,964
What is the purpose of the scales factor in Faster Rcnn Box Coder?
<p>I'm using the object detection api and tuning the parameters for a SSD task. My question refers to the box coder at <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/box_coders/faster_rcnn_box_coder.py" rel="nofollow noreferrer">https://github.com/tensorflow/models/blob/master/resea...
<p>I find the answer here <a href="https://leimao.github.io/blog/Bounding-Box-Encoding-Decoding/" rel="noreferrer">https://leimao.github.io/blog/Bounding-Box-Encoding-Decoding/</a>, where the variables are used as some sort of Representation Encoding With Variance. The question was also the subject of this issue <a hre...
tensorflow|deep-learning|conv-neural-network|object-detection
6
368,563
57,949,625
With pytorch DataLoader how to take in two ndarray (data & label)?
<p>I have a training data features in ndarray of shape (100, 400, 3) as it's 100 images of 20x20 with RGB channel and label in shape (100, ). Do I need to combine them into one dataset or how can I pass it to Pytorch dataLoader in order to iterate over image and label later? </p> <p>What I've tried so far</p> <pre><...
<p>You can <a href="https://pytorch.org/docs/stable/torch.html#torch.from_numpy" rel="nofollow noreferrer">convert</a> your data/label ndarrays to <code>torch.tensor</code> and use <a href="https://pytorch.org/docs/1.1.0/data.html#torch.utils.data.TensorDataset" rel="nofollow noreferrer"><code>torch.utils.data.TensorDa...
pytorch
2
368,564
58,006,616
How to get indices of a value in a hierarchical index series in pandas
<p>Suppose I have this data structure called <code>test</code>:</p> <pre><code>12 2 80.0 4 2.0 6 8.0 7 15.0 8 26.0 ... 1095 12 59.0 15 2.0 1098 8 6.0 13 16.0 1128 13 32.0 Length: 62, dtype: float </code></pre> <p>which is o...
<p>Slice index with integers for positions:</p> <pre><code>print (test.index[0]) (12, 2) print (test.index[2]) (12, 6) </code></pre>
python|pandas|multi-index
1
368,565
58,099,888
How to calculate median value for multiple geodata in one row/ cell/ unit
<p>These values are one(1) key-value pair. <br/>POLYGON consist of geodata pairs (epsg.io). I want to replace the long list of pairs with the median value.<br/><strong>How can I calculate the median?</strong> </p> <pre><code>stand_wkts_17518235_wkt': 'POLYGON ((492828.736516854 6954026.18089914,492829.429213483 695402...
<p>I am not sure what data types you are working to start with, but if you are able to get your pairs into a string, it is pretty straight-forward.</p> <pre><code>pairs = '492828.736516854 6954026.18089914,492829.429213483 6954026.56685419,492834.140449438 6954029.20224745,492808.438764045 6954067.00000026,492799.9320...
python|pandas|numpy|geospatial|median
0
368,566
58,117,928
RuntimeError: CUDA error: invalid argument
<p>It can run epoch 1 and eval successfully, but it fails when run epoch 2.</p> <pre><code>Train Epoch:1[655200/655800(100%)] loss:26.4959 lr:0.2050 Test Epoch:1 acc:0.973 val:0.895 Train Epoch:2[0/655800(0%)] loss:26.8068 lr:0.2051 File "train_11w.py", line 244, in main train(train_loader, model, optimizer, epoc...
<p>Although it is difficult to understand what's going wrong, I would suggest you do the following.</p> <ol> <li>Can you try to run your code with <code>CUDA_LAUNCH_BLOCKING=1 python script_name args</code>? The <code>CUDA_LAUNCH_BLOCKING=1</code> env variable makes sure to call all CUDA operations synchronously so th...
pytorch
0
368,567
58,145,700
Using Groupby to store value_counts in new column in Dask Dataframe
<p>I've used to use <a href="https://stackoverflow.com/a/17709453/4539956">this solution</a> to compute and store value_counts of a column in Pandas and store the results in a new column.</p> <p>Now I'm trying to do the same for a Dask Dataframe, but it causes the following error:</p> <pre class="lang-py prettyprint-...
<p>In case you don't need to stick with <code>transform</code> (which was introduced in the most recent dask version see <a href="https://github.com/dask/dask/pull/5327" rel="nofollow noreferrer">issue</a>) I suggest you to use a left merge as in the following code. </p> <pre class="lang-py prettyprint-override"><code...
python|pandas|dask
2
368,568
57,951,186
Why i am getting this error keyword:Borough
<p>I am a beginner in Python.I merged two <code>columnsAfter</code> that i tried to change 'not assigned' value of a column with another column value. I cant do that. If I use <code>premodified dataframe</code> then I can change.</p> <p>I scraped a table from a page then modifying the data in that dataframe.</p> <pre...
<p>Reason of your <code>keyerror</code> is <code>Neighbourhood</code> is not column, but index level, solution is add <code>reset_index</code>:</p> <pre><code>toronto_df1= pd.read_html('https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_M')[0] #boolean indexing toronto_df1 = toronto_df1.loc[toronto...
python|pandas
0
368,569
58,156,384
TypeError: 'module' object is not callable Tensorboard in Keras
<p>I am implementing a RL agent with policy gradient method. I define a dense network for actor and another dense network for critic. For example, my critic network is:</p> <pre><code>state_input = Input(shape=(self.num_states,)) x = Dense(self.hidden_size, activation='tanh')(state_input) for _ in range(self.num_layer...
<blockquote> <p>TypeError: 'module' object is not callable in your case is caused by time module</p> </blockquote> <p>I am assuming that you imported time module as </p> <pre><code>import time </code></pre> <p>and called the function time()</p> <pre><code>tensorboard = TensorBoard(log_dir="/logs/{}".format...
python|tensorflow|keras|tensorboard|keras-rl
4
368,570
58,034,237
Why does PANDAS only see one column to csv dataset with numerous columns?
<p>I am new to and PANDAS and I am trying to work out why the shape of this csv dataset[<a href="https://www.kaggle.com/vfoufikos/airbnb-analysis-lisbon][1]" rel="nofollow noreferrer">https://www.kaggle.com/vfoufikos/airbnb-analysis-lisbon][1]</a> is being shown as: (237, 1)? As it appears that the dataset has 20 colum...
<p>You could use a <code>usecols</code> option to select the columns youd like to use. For example if you wanted to store dataset columns into 'df' you could use: </p> <pre><code>df = pd.read_csv(...., usecols=['col1', 'col2',..., 'coln']) </code></pre> <p>If you'd like to select all the data without specifying which...
python|pandas|csv|dataframe
0
368,571
58,071,982
read csv in a for loop using pandas
<pre><code>inp_file=os.getcwd() files_comp = pd.read_csv(inp_file,"B00234*.csv", na_values = missing_values, nrows=10) for f in files_comp: df_calculated = pd.read_csv(f, na_values = missing_values, nrows=10) col_length=len(df.columns)-1 </code></pre> <p>Hi folks, How can I read 4 csv files in a for a loop....
<p>You basically need this:</p> <ol> <li>Get a list of all target files. <code>files=os.listdir(path)</code> and then keep only the filenames that start with your pattern and end with <code>.csv</code>. You could also improve it using regular expression (by importing <code>re</code> library for more sophistication, or...
python|pandas|data-analysis
2
368,572
58,042,869
Pandas - how to create a new column that takes value from colum of previous row or next row if first row
<p>Given a data data like below </p> <pre><code>Time Col01 Col02 05:17:55.703000 NaN NaN 05:17:55.703000 891 12 05:17:55.703000 891 13 05:17:55.703000 891 15 05:17:55.703000 891 16 05:17:55.703000 891 17 05:17:55.703000 891 18 05:17:55.707000 892 0 05:17:55.707000 892 1 05:17:55.707000 892 5 05:17:55.707000 8...
<p>Fill in the correct order, first forward then backward (to get just the first row, if null).</p> <pre><code>pd.concat([df, df[['Col01', 'Col02']].ffill().bfill(downcast='infer').add_suffix('new')], axis=1) </code></pre> <hr> <pre><code> Time Col01 Col02 Col01new Col02new 0 05:17:55.703000 N...
python|pandas|dataframe
1
368,573
58,026,842
XlsxWriter with Pandas dataframe thousand separator
<p>To my little knowledge, Xlsxwriter may be the best package to format my numbers with thousand separator. I have read xlsxwriter documents many times, still very confusing, I think others may have the same problem, thus I post my question here. I have a pandas dataframe DF_T_1_EQUITY_CHANGE_Summary_ADE, and I want to...
<p>It should work. You need to move the <code>add_format()</code> a bit later in your code, after you get a reference to the workbook object. Here is an example:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd # Create a Pandas dataframe from some data. df = pd.DataFrame({'Data': [1234.56, 23...
python|excel|pandas|xlsxwriter
6
368,574
57,762,442
Did dropna() on dataframe, why is the number of rows lower than expected?
<p>I have a Dataframe where most columns have 10866 non-null values, except a couple of columns with fewer. The column with the least number of non-null values is "keywords" (9373). So when I drop the NA-values from the Dataframe , I expect the number of non-null values for each column to be equal to the number of non-...
<p>Consider the following code:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np df = pd.DataFrame( {"name": ['A', 'B', 'C'], 1: [1, 2, np.nan], 2: [1, np.nan, 3], 3: [np.nan, 2, 3]}) print(df) df.dropna(inplace=True) print(df) </code></pre> <p>What do you ...
python|pandas|dataframe|na
3
368,575
57,765,137
nansum only if at least one value is not nan - numpy
<p>I want to execute nansum function by row only if at least one value in the row is not nan. So if all values in the row is nan, the sum should be nan not zero.</p> <pre class="lang-py prettyprint-override"><code>a = np.array([[1],[2],[3],[4],[np.nan],[np.nan]]) b = np.array([[1],[2],[3],[4],[np.nan],[1]]) #a+b shoul...
<p>1.8 version on <code>nansum</code> <a href="https://github.com/numpy/numpy/blob/maintenance/1.8.x/numpy/lib/nanfunctions.py" rel="nofollow noreferrer">https://github.com/numpy/numpy/blob/maintenance/1.8.x/numpy/lib/nanfunctions.py</a></p> <p>was</p> <pre><code>def nansum(a, axis=None, dtype=None, out=None, keepdim...
python|numpy
1
368,576
57,793,211
Calculating current, min, max, mean monthly growth from pandas dataframe
<p>I have a dataset similar to the one below: </p> <pre><code>product_ID month amount_sold 1 1 23 1 2 34 1 3 85 2 1 47 2 2 28 2 3 9 3 1 73 3 2 8...
<p>You can use a <code>pivot_table</code> withh <code>pct_change()</code> on <code>axis=1</code> , then create a dictionary with desired series and create a df:</p> <pre><code>m=df.pivot_table(index='product_ID',columns='month',values='amount_sold').pct_change(axis=1) d={'avg_monthly_growth':m.mean(axis=1)*100,'lowest...
python|pandas|dataframe
1
368,577
57,892,112
Select a number randomly with probability proportional to its magnitude from the given array of n elements
<p>Ex 1: A = [0 5 27 6 13 28 100 45 10 79] let f(x) denote the number of times x getting selected in 100 experiments. f(100) > f(79) > f(45) > f(28) > f(27) > f(13) > f(10) > f(6) > f(5) > f(0)</p> <p>My code:</p> <pre><code>def pick_a_number_from_list(A,l): Sum = 0 #l = len(A) for i in range(l): ...
<pre><code>sum1=0; for i in A: sum1+=i; x=0 list1=[] for i in A: list1.append(x+i/sum1) x=x+i/sum1; #list1 contsins cumulative sum bit=uniform(0,1) for i in range (0,len(list1)): if bit&lt;list1[i]: return A[i] </code></pre> <p>you may use this</p>
python-3.x|pandas|random
3
368,578
57,842,300
How to check if a word in one csv exist in another column of another csv file
<p>I have 2 csv file, one is dictionary.csv which contains a list of words, and another is story.csv. In the story.csv there are many columns, and in one of the columns contains a lots of words called news_story. I wanted to check if the list of words from dictionary.csv exists in the news_story column. Afterwards i wa...
<p>First convert column to Series with <code>header=None</code> for avoid remove first value with <code>squeeze=True</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="nofollow noreferrer"><code>read_csv</code></a>:</p> <pre><code>dictionary=pd.read_csv("dictionary....
python-3.x|pandas|csv
1
368,579
57,895,463
How to convert a CSV file with strange delimiter to a dataframe in Python using pandas library
<p>I am attempting to convert a CSV file to a dataframe using Python but the delimiter is causing issues.</p> <p>The CSV file is an output from a software that arrange the data into a single line mainly separated by: ","</p> <p>There are only two lines in the CSV file. The first one is:</p> <pre><code>Date," 2015-0...
<p>In this line - <code>data = pd.read_csv("csv_file_one_line.csv", sep = '","' , engine = 'python')</code>, you are separating based on <code>','</code>, not simply <code>,</code>. </p> <p>Just use the comma, not apostrophes and a comma.</p>
python|pandas
0
368,580
57,995,707
Strange behavior na_values parameter in read_csv
<p>I am trying to read a csv file that contains in some columns the string 'na' which I want to be read as 'NaN'. For that reason I use the parameter na_values:</p> <pre class="lang-py prettyprint-override"><code>data=pd.read_csv('myFile.csv', header=1, skipfooter=1, na_values=['na']) </code></pre> <p>But in the data...
<p>You need to set the keep_default_na parameter for proper parsing of NaN values.</p>
python|pandas
0
368,581
58,082,873
Can I forward recalculate a value in a pandas dataframe when a value has been reset, e.g. a water meter
<p>I want to forward fill my water meter reading data when resets occur so that the data is clean for analysis. A reset is when the value in the next row is less than the previous one.</p> <p>My python pandas dataframe looks like this:-</p> <pre><code> water 0 31031 1 31037 2 31038 3 31043 ...
<p>You can find where the resets are, take the previous values, and add to the subsequence:</p> <pre><code># resets resets = df.water.diff().le(0) # reading at resets # cumsum is used to accumulate readings readings = df.water.shift().where(resets).fillna(0).cumsum() df.water += readings </code></pre> <p>Output:</p...
python|pandas|dataframe
0
368,582
57,956,445
Error using categorical column in geom_density
<p>When converting a column to a type categorical, and setting the some aesthetics property (aes()) to use it, I'm getting the following error:</p> <p><code>NotImplementedError: isna is not defined for MultiIndex</code></p> <p>For example, here's a reproducible example:</p> <pre><code>randCat = np.random.randint(0,2...
<p>I overcame the "fill" issue using the seaborn package.</p> <pre><code>import matplotlib.pyplot as plt import seaborn as sns sns.kdeplot(df[df['cat'] == 'firstCat']['proj'], shade=True, label='firstCat') sns.kdeplot(df[df['cat'] == 'secondCat']['proj'], shade=True, label='secondCat') plt.show() </code></pre> <p><a...
python|python-3.x|pandas|python-ggplot
0
368,583
57,808,480
regex on pandas dataframe column having string representation of lists
<h2>Example DataFrame:</h2> <pre><code>&gt;&gt;&gt; df color 0 ['Light_Blue','Green','Dark_Blue'] 1 ['Sky_Blue','Black','White', 'Yellow','Gray'] 2 ['White','Jet_Blue','Pink', 'Tan','Brown', 'Purple'] </code></pre> <h2>Tried Following with regex:</h2> <p>Using fol...
<p>I'd suggest you use a list comprehension for such a problem:</p> <pre><code>df['color'] = [[i for i in r if not i.endswith(tuple(['_Blue', '_']))] for r in df.color] color 0 [Green] 1 [Black, White, Yellow, Gray] 2 [White, Pink, Tan, Brown, Purple] ...
python|regex|python-3.x|pandas|numpy
1
368,584
58,093,664
How to check if values in one dataframe column are contained in another entire column?
<p>In my project I need to check if some value exists in entire dataframe column. Example dataframe:</p> <pre><code>df=pd.DataFrame([['abc', 'a'], ['def', 'x'], ['aef', 'f']]) df.columns=['a', 'b'] &gt;&gt;&gt;df a b 0 abc a 1 def x 2 aef f </code></pre> <p>This static code works well:</p> <pre><code>df[...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.extractall.html" rel="nofollow noreferrer"><code>Series.str.extractall</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer"><code>Series.isin</code...
pandas|dataframe
1
368,585
34,055,584
Python Pandas: String Contains and Doesn't Contain
<p>I'm trying to match rows of a Pandas DataFrame that contains and doesn't contain certain strings. For example:</p> <pre><code>import pandas df = pandas.Series(['ab1', 'ab2', 'b2', 'c3']) df[df.str.contains("b")] </code></pre> <p>Output:</p> <pre><code>0 ab1 1 ab2 2 b2 dtype: object </code></pre> <p>Des...
<p>You're almost there, you just haven't got the syntax quite right, it should be: </p> <pre><code>df[(df.str.contains("b") == True) &amp; (df.str.contains("a") == False)] </code></pre> <p>Another approach which might be cleaner if you have a lot of conditions to apply would to be to chain your filters together with ...
python|pandas|dataframe
14
368,586
34,013,001
Summarizing a CSV data into data frame by averaging based on two headers in Pandas
<p>I have the following CSV <a href="http://dpaste.com/3J2TRSV.txt" rel="nofollow">data</a>:</p> <pre><code>id,gene,celltype,stem,stem,stem,bcell,bcell,tcell id,gene,organs,bm,bm,fl,pt,pt,bm 134,foo,about_foo,20,10,11,23,22,79 222,bar,about_bar,17,13,55,12,13,88 </code></pre> <p>Notice that it contains two headers. W...
<pre><code>df = pd.read_csv(join(DESKTOP, 'bio.csv'), header=None, index_col=[1,2]).iloc[:, 1:] df.columns = pd.MultiIndex.from_arrays(df.ix[:2].values) df = df.ix[2:].astype(int) df.index.names = ['cell', 'organ'] df = df.reset_index('organ', drop=True) avg = df.groupby(level=[0, 1], axis=1).mean() result = avg.stac...
python|pandas
2
368,587
34,068,204
matrix divided by rows of another matrix, without a loop in numpy
<p>What is the equivalent numpy implementation of the code below without using a loop?</p> <pre><code>dt = np.dtype(np.float32) a=[[12,3], [2,4], [2,4],] b=[[12,3,2,3], [2,4,4,5]] a=np.asarray(a,dtype=dt) b=np.asarray(b,dtype=dt) print(a.shape) print(b.shape) ainvb=np.zeros((3,2,4)) for i in range(4): a...
<p>For a numpy solution, make use of array broadcasting by inserting singleton dimensions in your arrays:</p> <pre><code> ainvb2=a[:,:,None]/b[None,:,:] </code></pre> <p>This works by transforming <code>a</code> to shape <code>(3,2,1)</code> and <code>b</code> to shape <code>(1,2,4)</code>. They can then be broadcast...
python|numpy|matrix|linear-algebra|division
3
368,588
34,258,669
Tensorflow : one hot encoding
<p>The following code works fine, but uses eval() which I think would be inefficient. Is there a better way to achieve the same ?</p> <pre><code>import tensorflow as tf import numpy as np sess = tf.Session() t = tf.constant([[4,5.1,6.3,5,6.5,7.2,9.3,7,1,1.4],[4,5.1,9.3,5,6.5,7.2,1.3,7,1,1.4],[4,3.1,6.3,5,6.5,3.2,5.3,...
<p>One way to achieve it is to compute max on each row and then compare each element to that value. I don't have tensor flow installed on this machine, so can't provide you with the exact code, but it will be along the lines of this:</p> <pre><code>z1 = tf.equal(t, tf.reduce_max(t, reduction_indices=[1], keep_dims=Tru...
eval|tensorflow|one-hot-encoding
3
368,589
34,387,349
Set matplotlib grid ticks based on specific dates
<p>I am plotting Pandas Series datetimes of 30 years. The x-axis are dates:</p> <pre><code>Datetime 1965-06-08 3545 1965-06-09 6378 1965-06-10 9857 1965-06-11 2528 .... Freq: W-SUN, dtype: int64 </code></pre> <p>I would like to have a "minor tick" at each month, and a "major tick" at each year. </p> <p>...
<p>You want <a href="http://matplotlib.org/api/dates_api.html#matplotlib.dates.YearLocator" rel="nofollow noreferrer"><code>matplotlib.dates.YearLocator</code></a> and <a href="http://matplotlib.org/api/dates_api.html#matplotlib.dates.MonthLocator" rel="nofollow noreferrer"><code>matplotlib.dates.MonthLocator</code></a...
python|numpy|pandas|matplotlib
2
368,590
34,276,280
AttributeError: 'module' object has no attribute 'MutableMapping'
<p>I followed the instructions for installing Google Tensorflow and its dependencies on an Ubuntu 14.04 g2.8xlarge aws instance. While trying to run the example problems, I'm running into the error posted below. Any help would be greatly appreciated. Thanks.</p> <pre><code>Traceback (most recent call last): File "co...
<p>This sounds like an incompatibility between TensorFlow and the version of Protocol Buffers that's installed on your machine. The two best options are:</p> <ol> <li><p>Try to upgrade the Protobuf library in <code>/usr/local/lib/python2.7/dist-packages/google/protobuf/</code> to version 3.0.0a3 or higher.</p></li> <l...
python|ubuntu|tensorflow
5
368,591
34,045,672
pip install numpy - fails to install although there are no errors
<p>I'm using Linux AMI on Amazon EC2 and I would like to install <code>numpy</code> and <code>scipy</code>. In theory, it should be quite straightforward, but I'm runnign into problems.</p> <p>Here are my steps:</p> <pre><code>&gt; sudo alternatives --set python /usr/bin/python3.4 &gt; sudo virtualenv -p python3.4 my...
<p>When you set up your virtualenv to use python3 you also have to use <code>pip3</code></p> <pre><code>virtualenv -p python3.4 env source env/bin/activate pip3 install numpy </code></pre>
python|numpy|amazon-ec2
2
368,592
34,298,482
python read 2d in to a 1d array
<p>I have a 2D txt file:</p> <pre><code>[[1406], [1408], [1402], [1394, 102462], [1393], [20388], [20387, 20386], [1386], [1443, 1446, 766], [1432, 1438, 1430, 1416], [1442], [1434], [1430, 1416, 1417, 1419, 3446], [1429], [20011], [20015], [4435], [4441], [4443], [4444], [4448], [2433, 1413, 1418], [4450], [3444], [2...
<p>I don't know what functionality numpy has for this, but since your text file happens to be valid JSON, you could just load it as JSON, flatten it, and then convert the result to a numpy array.</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; with open('muti.txt', 'r') as f: arr =...
python|python-2.7|numpy
3
368,593
34,072,966
Pandas DF, conditional selection in unequal columns
<p>I have a DF created by merging my original DF and a resampled version of the original. The resampled version is <code>Bin_time</code> and <code>ave_knots</code> which was merged on the joint field <code>ID</code> to create this DF. </p> <pre><code> id trip_id knots times Bin_time ave_...
<p>I would start with keeping the resampled output separate from the original DataFrame. I've copied your examples into the following code in a way that hopefully mimics your actual data (note that the date columns should be interpreted as actual datetime objects, or this won't work).</p> <pre><code>import pandas as ...
python|pandas
2
368,594
34,341,112
pandas build on Cygwin
<p>I tried building pandas on Cygwin and run into an error building pandas.msgpack._packer:</p> <pre><code>building 'pandas.msgpack._packer' extension </code></pre> <p>The error is:</p> <pre><code>gcc: error: spawn: No such file or directory </code></pre> <p>And here's the build command:</p> <pre><code>gcc -Wno-un...
<p>Install the following packages in cygwin :</p> <pre><code>python2-numpy python2-six python2-wheel python2-setuptools python2-pip python2-cython gcc-core gcc-fortran gcc-g++ make wget </code></pre> <p>And then in Cygwin Terminal, build and install </p> <pre><code>pip2 install pytz python-dateutil pip2 install pand...
python|pandas|cygwin
6
368,595
34,225,611
Using tkinter Entries for variables in external functions
<p>I am trying to link entry variables to a function within Tkinter. I have 16 entry / variables that I want to use in my function. However, I'm struggling with the interface between the entry and the assigning of the variable. </p> <p>my code: </p> <pre><code>import Tkinter import pandas as pd import numpy as np c...
<p>You can get out the values from a box by calling its "textvariable" like</p> <pre><code>c2_low.get() </code></pre> <p>So if you change those variable to self.c2_low, self.c2_high etc. you will be able to call them inside your simulation function like:</p> <pre><code>import Tkinter import pandas as pd import numpy...
python|pandas|tkinter|tkinter-canvas
1
368,596
34,237,462
Selecting column before nth breaks group indices
<p>I try to extract the column <code>c</code> from the first of each group's rows, but struggle to understand why the group indices aren't preserved with the <code>g['c'].nth(0)</code> approach. Any idea?</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({'a': [1, 1, 2, 2], 'b': ['b', 'b', 'b', 'a'], 'c': [1, 2, 3, 4]}) &...
<p>I add new column <code>d</code> for better testing:</p> <pre><code>import pandas as pd import numpy as np import io df = pd.DataFrame({'a': [1, 1, 2, 2], 'b': ['b', 'b', 'b', 'a'], 'c': [1, 2, 3, 4], 'd': [1, 2, 3, 4]}) print df # a b c d #0 1 b 1 1 #1 1 b 2 2 #2 2 b 3 3 #3 2 a 4 4 g = df.gro...
python|pandas
1
368,597
34,372,160
Python Array issue - string indices must be integers not tuple
<p>Consider the following code:</p> <pre><code>handInformation = [ "Thumb"[ "MetaCarpal"["start"[0,0,0], "end"[0,0,0], "direction"[0,0,0]], "Proximal"["start"[0,0,0], "end"[0,0,0], "direction"[0,0,0]], "Intermediate"["start"[0,0,0], "end"[0,0,0], "direction"[0,0,0]], "Distal"["start"[0,0,0], "end"[0,0,0], "direction"...
<p>You are getting downvoted almost certainly because your code syntax is wrong - "string"[0,0,0] isn't a valid construct in Python.</p> <p>You could use dictionaries, with not dissimilar syntax like this:</p> <pre><code>handInformation = { "Thumb":{ "MetaCarpal": {"start":[0,0,0], "end":[0,0,0], "direction":[0,0,0]}...
python|arrays|numpy
2
368,598
37,037,581
Plotting of Dataframe with two columns having repetitive values
<p>I have a dataframe with repetitive data and I want to plot it (may be using seaborn). column1 has 4 different strings which repeat 6 times each. column2 has their corresponding values in decimals(float). I have to boxplot it with the 4 distinct names on the x-axis and their corresponding values on the y-axis </p> <...
<p>You might want to try <code>df.boxplot(by='col_A', column="col_C",)</code></p>
python|numpy|matplotlib|dataframe|seaborn
0
368,599
37,003,929
Find all entries within a certain interval of each other in Pandas
<p>I need to find all entries that are contained within a certain interval (error) from each other, for each column of a pandas DataFrame (and group them by index). Example for a +/- 0.2 interval:</p> <pre><code>myDataFrame: A B C 0 1.1 1.3 1.5 1 0.7 0.1 -0.5 2 1.2 1.9 1.3 3 0.1 0.0 -0.3 4 0.2 ...
<p>You can use pandas cut function to bin the variables.</p> <pre><code>import pandas as pd df.loc[:, 'C_bins'] = pd.cut(df.C, bins=[.2*x for x in range(-10, 10)]) </code></pre> <p>yields </p> <pre><code> A B C C_bins 0 1.1 1.3 1.5 (1.4, 1.6] 1 0.7 0.1 -0.5 (-0.6, -0.4] 2 1.2 1.9 1.3...
python|python-2.7|pandas|dataframe
0