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
354,300
61,504,200
Convert String to Integer within Column in Dataframe (5 Star Rating = 5)
<p>I want to convert a column containing strings of reviews such as 5.0 out of 5 stars to an integer. </p> <pre><code>0 5.0 out of 5 stars 1 2.0 out of 5 stars 2 5.0 out of 5 stars 3 5.0 out of 5 stars 4 5.0 out of 5 stars 5 5.0 out of 5 stars 6 4.0 out of 5 stars 7 5.0 out of 5 stars 8 5.0 ...
<p>Try splitting the string and converting the first element to float:</p> <pre><code>df['StarRatingNumeric'] = df.StarRating.apply(lambda r: float(r.split()[0])) </code></pre> <p>or if you need integer data type:</p> <pre><code>df['StarRatingNumeric'] = df.StarRating.apply(lambda r: int(float(r.split()[0]))) </code...
python|pandas|for-loop
0
354,301
61,218,872
Pandas: Add a column of list of values from other columns based on an index list in another column
<p>This is the original data frame, where group contains list of index values of group which each person belongs to.</p> <pre><code> Name Group 0 Bob [0, 1] 1 April [0, 1] 2 Amy [2, 3] 3 Linda [2, 3] </code></pre> <p>This is what I...
<p>I think you need <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.explode.html" rel="nofollow noreferrer"><code>Series.explode</code></a> + <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html" rel="nofollow noreferrer"><code>Series.map</code></a...
python|pandas
1
354,302
61,506,162
Session crash in Colab due to excess usage of RAM
<p>I'm getting the following runtime error when I tried to create a huge 3D numpy array. <strong>Your session crashed after using all available RAM.</strong></p> <p>This is the code that's causing the error,</p> <pre><code>decoder_output_one_hot = np.zeros((30000, 23, 20000), dtype='float32'). </code></pre> <p>Why i...
<p>Your are attempting to create an array with 30000 x 23 x 20000 = 13,800,000,000 entries. Each entry is a 32-bit floating point number, so the total number of bytes is 13,800,000,000 x (32 / 8) = 55,200,000,000: in other words, your array would occupy over 50GB in RAM, twice what you have available.</p>
numpy|deep-learning|google-colaboratory|ram
3
354,303
61,210,787
Using pandas to look up the values of one column from the closest match between another column and multiple inputs
<p>I have two data frames one is a reference I am comparing the second data frame to the first column of the reference to find the closest matches and then returning the corresponding item from the second column of the reference data frame. I am trying to find a faster method to do this than what I’m currently doing wh...
<p>This is <code>merge_asof</code>:</p> <pre><code># convert reference values to float references['A'] = references['A'].astype('float64') pd.merge_asof(df, references, left_on='a', right_on='A', direction='nearest' ) </code></pre> <p>Output:</p> <pre><code> a A B ...
python|pandas
2
354,304
61,433,414
Which values to use when feeding placeholders in Tensorflow?
<p>In the code below, there are a number of tensor operations and calculations. I'd like to see the results of some of those calculations so I can better understand them. Specifically I'd like to see what h looks like during graph execution using <code>print(Session.Run(h))</code>. However, the calculations are depende...
<p>When you use an interactive session you can just set the values in python x = 57, bypassing the placeholder entirely, then evaluate the rest of the graph however you want. </p>
python|tensorflow
0
354,305
61,582,280
Is there a way in python pandas to do "Text to Columns" by location (not by a delimiter) like in excel?
<p>I'm using Vote History data from the Secretary of State, however the .txt file they gave me is 7 million rows, where each row is a string with 27 characters. The first 3 characters are a code for the county. The next 8 characters are the registration ID, the next 8 characters are the date voted, etc. I can't do text...
<p>Simplest I can make it:</p> <pre><code>import pandas as pd sample_lines = ['0010000413707312012026R','0010000413708212012027R','0010000413711062012029','0010004535307312012026D]'] COLUMN_NAMES = ['A','B','C','D','E'] df = pd.DataFrame(columns=COLUMN_NAMES) for line in sample_lines: row = [line[0:3], line[3:11...
python|pandas|data-mining
1
354,306
61,466,920
Standard deviation of time series data on two columns
<p>I have a data frame with two-columns of data for a day with a time series index. The sample data is in 1-minute and I want to create a 5-minute data frame where a 5-minute interval will be flagged false when the standard deviation of the 5 samples in the respective 5-minute is not deviating by 5% of the mean of the ...
<p>You can use the resample method of the pandas data frames, for that the dataframe most be index with a time stamp. Here an example:</p> <pre><code>import pandas as pd import numpy as np dates = pd.date_range('1/1/2020', periods=30) df = pd.DataFrame(np.random.randn(30,2), index=dates, columns=['X','Y']) df.head() ...
python|pandas|statistics|time-series|standard-deviation
1
354,307
61,387,313
Python: Finding time taken for each event in dataframe based on condition
<p>I have a df with two columns, timestamp &amp; eventType.</p> timestamp is ordered in chronological order, and eventType can be either ['start', 'change', 'end', resolve].</p></p> <pre><code>['start', 'change'] denotes the start of an event ['end','resolve'] denotes the end of an event createdTime action...
<p>Better late than never?</p> <pre><code>df['createdTime'] = pd.to_datetime(df.createdTime) starts = ['start', 'change'] ends = ['end','resolve'] prev_status = 'end' spans = [] for i in range(len(df)): curr_status = df.actionName[i] if curr_status in starts and prev_status in starts: pass elif c...
python|pandas|dataframe|time-series
0
354,308
61,255,108
Python numpy ravel function not flattening array
<p>I have an array of arrays called x and I am trying to do ravel on it but the result is the same x. It is not flattening anything. I have also tried the function flatten(). Can someone explain me why is this happening?</p> <pre><code>x = np.array([np.array(['0 &lt;= ... &lt; 200 DM', '&lt; 0 DM', 'no checking accoun...
<pre><code>In [455]: x = np.array([np.array(['0 &lt;= ... &lt; 200 DM', '&lt; 0 DM', 'no checking account'], dtype=object), ...: ...: np.array(['critical account/ other credits existing (not at this bank)', ...: 'existing credits paid back duly till now'], dtype=object), ...: ...
python|numpy
0
354,309
61,319,533
Pandas installation with all dependencies
<p>i am new to python. i am using python 3.7 and installed pandas using pip. when i checked for pandas version i found all the dependencies are not installed . so i read somewhere anaconda installation will install all the dependent packages. so i have installed anaconda still when i search for python version it shows ...
<p>The process I follow:</p> <ol> <li>Install anaconda from this link <a href="https://www.anaconda.com/distribution/" rel="nofollow noreferrer">https://www.anaconda.com/distribution/</a></li> <li>Add the Anaconda program directory to your Path environment variable. See here > <a href="https://www.quora.com/How-can-I-...
python|pandas
0
354,310
61,529,476
Why does a specific numpy implementation of the Gauss-Jacobi method significantly reduce iterations?
<p>When implementing the Gauss Jacobi algorithm in python I found that two different implementations take a significantly different number of iterations to converge.</p> <p>The first implementation is what I originally came up with</p> <pre class="lang-py prettyprint-override"><code>import numpy as np def GaussJacobi...
<p>Your second implementation does <code>N</code> <em>actual</em> iterations per increment of <code>k</code>, since the assignment to <code>x</code> already covers the <strong>entire</strong> vector. Its “advantage” thus increases with problem size.</p>
python|numpy|linear-algebra
1
354,311
61,556,827
Parsing a list of lists to a data frame in pandas
<p>I have list of lists. Below is how my list looks like, I want to parse it into a data frame with continuation of values with columns = A,B,C</p> <pre><code>[ A B C 0 1 2 3 1 1 2 3 2 1 2 3 3 1 2 3 A B C 0 4 5 6 1 4 5 6 2 4 5 6 3 4 5 6 ] </code></pre> <...
<p>Try this:</p> <pre><code>import pandas as pd list1=[] count=0 while count&lt;len(myList): list2= myList[count] list1.append(list2) #print(list2) count+=1 df = pd.concat(list1) print(df) </code></pre> <p><code>myList</code> : List which contains sub-lists</p> <p><code>list2</code> : First it takes ...
python|pandas|list|dataframe
0
354,312
61,415,589
Get value of 'cell' in one dataframe based on another dataframe using pandas conditions
<p>Given DF1:</p> <pre><code>Title | Origin | % Analyst Referral 3 Analyst University 10 Manager University 1 </code></pre> <p>and DF2:</p> <pre><code>Title | Referral | University Analyst Manager </code></pre> <p>I'm trying set the values inside DF2 ...
<p>just use pivot, no need for logic:</p> <pre><code>s = """Title|Origin|% Analyst|Referral|3 Analyst|University|10 Manager|University|1""" df = pd.read_csv(StringIO(s), sep='|') df.pivot('Title', 'Origin', '%') Origin Referral University Title Analyst 3.0 10.0 Manager ...
python|pandas
1
354,313
61,475,874
Convert a sparse matrix to dataframe
<p>I have a sparse matrix that stores computed similarities between a set of documents. The matrix is an ndarray.</p> <pre><code> 0 1 2 3 4 0 1.000000 0.000000 0.000000 0.000000 0.000000 1 0.000000 1.000000 0.067279 0.000000 0.000000 2 ...
<p>Convert the dataframe to an array:</p> <pre><code>x = df.to_numpy() </code></pre> <p>Get a list of non-diagonal non-zero entries from the sparse symmetric distance matrix:</p> <pre><code>i, j = np.triu_indices_from(x, k=1) v = x[i, j] ijv = np.concatenate((i, j, v)).reshape(3, -1).T ijv = ijv[v != 0.0] </code></p...
pandas|numpy|sparse-matrix
2
354,314
61,363,873
Pandas group by max value all columns except datetime
<p>I am having an issue with a dateframe I have created. It has multiple columns along with the 2 columsn im trying to group by and its a date time. </p> <p>the table is as follows- </p> <pre><code>product number color solddate price TV 123 green 20/04/2020 50 TV 123 green 19/04/2020 100 </...
<p>I think this <a href="https://stackoverflow.com/questions/47360510/pandas-groupby-and-aggregation-output-should-include-all-the-original-columns-i">post</a> might be relevant. </p> <p>Also, this method might be useful ( came across this <a href="https://stackoverflow.com/questions/23394476/keep-other-columns-when-d...
python|pandas
0
354,315
61,290,287
How can I slice a PyTorch tensor with another tensor?
<p>I have:</p> <pre><code>inp = torch.randn(4, 1040, 161) </code></pre> <p>and I have another tensor called <code>indices</code> with values:</p> <pre><code>tensor([[124, 583, 158, 529], [172, 631, 206, 577]], device='cuda:0') </code></pre> <p>I want the equivalent of:</p> <pre><code>inp0 = inp[:,124:172,...
<p>Here you go (EDIT: you probably need to copy tensors to cpu using <code>tensor=tensor.cpu()</code> before doing following operations):</p> <pre><code>index = tensor([[124, 583, 158, 529], [172, 631, 206, 577]], device='cuda:0') #create a concatenated list of ranges of indices you desire to slice indexer = np.r_...
python|numpy|pytorch|tensor
2
354,316
61,341,838
Vectorisation of coordinate distances in Numpy
<p>I'm trying to understand Numpy by applying vectorisation. I'm trying to find the fastest function to do it. </p> <pre><code>def get_distances3(coordinates): return np.linalg.norm( coordinates[:, None, :] - coordinates[None, :, :], axis=-1) coordinates = np.random.rand(1000, 3) %timeit get_distan...
<p>You're not calling <code>np.vectorize()</code> correctly. I suggest referring to <a href="https://numpy.org/doc/stable/reference/generated/numpy.vectorize.html" rel="nofollow noreferrer">the documentation</a>.</p> <p>Vectorize takes as its argument <em>a function</em> that is written to operate on <em>scalar</em> ...
python|numpy|vectorization
1
354,317
61,434,497
Pandas pivot table gives "FutureWarning: Sorting because non-concatenation axis is not aligned"
<p>I have the following DataFrame:</p> <pre><code>df = pd.DataFrame({'category':['A', 'B', 'C', 'C'], 'bar':[2, 5, float('nan'), float('nan')]}) </code></pre> <p>And then I have just one line of code, where I'm trying to apply two aggregation functions on a column in my DataFrame, grouped by value...
<p>I was able to replicate the issue on pandas 0.25.1, the waning is related to <code>pandas.core.reshape.pivot.py</code> that includes the following statement</p> <pre><code># line 56 return concat(pieces, keys=keys, axis=1) </code></pre> <p>Concat is causing the warning. <code>pieces</code> is a list of dataframes ...
python|pandas|warnings|concat
1
354,318
61,320,589
Combining Two Pandas Series gives TypeError: 'DataFrame' object is not callable
<p>I am trying to combine two pandas series, values from one dataset need to be added to another one. I am getting an error so I have prepared a simple test case following documentation: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.combine.html" rel="nofollow noreferrer">https://pan...
<p>I have reused the code you have written here additionally with the import line as well:</p> <pre><code>import pandas as pd s1 = pd.Series({'falcon': 330.0, 'eagle': 160.0}) s2 = pd.Series({'falcon': 345.0, 'eagle': 200.0, 'duck': 30.0}) s1.combine(s2, max) </code></pre> <p>Here is the result:</p> <pre><co...
python|pandas
0
354,319
61,246,705
Filling Null Values based on conditions on other columns
<p>I want to fill the Null values in the first column based on the value of the 2nd column. (For example)</p> <ol> <li>For "Apples" in col2, the value should be 12 in places of Nan in the col1 </li> <li>For "Vegies", in col2 the value should be 134 in place of Nan in col1</li> </ol> <p>For every description, there ...
<p>**Reupdate</p> <p>Here, I replicate your DF, and the implementation:</p> <pre><code>import pandas as pd import numpy as np l1 = [12, 134, 23, np.nan, np.nan, 324, np.nan,np.nan,np.nan,np.nan] l2 = ["Apple","Vegies","Oranges","Apples","Vegies","Sugar","Apples","Melon","Melon","Grapes"] df = pd.DataFrame(l1, columns...
python|pandas|dataframe|data-cleaning
1
354,320
61,546,129
Selecting rows with a value of False
<p>I have a data set and during validation I have marked the "rejected" rows by masking the bad cell with the boolean False. I am looking to split that dataframe into two, the good and the bad data. The following code works perfectly for grabbing the good data from the data frame. It selects the rows where that do not...
<p>Answer per @QuangHoang.</p> <p>Replacing the for-loop with the below: df[df.eq(False).any(1)]</p> <p>Reason: 0==False is True</p>
python|pandas
0
354,321
61,389,738
Failed to find data adapter that can handle input: <class 'numpy.ndarray'>, (<class 'list'> c
<p>Below I would like to store the images in my laptop to the variable called X_data by using the function of <code>glob</code> and then split it into training and test set before testing the model.</p> <pre><code> import cv2 import numpy as np import tensorflow as tf from tensorflow.keras import datasets, layers, ...
<p>I see couple of problems in your code:</p> <ol> <li>Both <code>train</code> and <code>test</code> are <code>Lists</code>, not <code>Numpy Arrays</code>. Same might be the case with <code>Labels</code> (that part of code is not shared).</li> <li><p>The part of code, </p> <p><code>X_data = [] files = glob.glob ("*....
python|tensorflow|keras
1
354,322
61,349,166
Python - String Formatting (How to Limit Decimal Without the Float Getting Converted Into String)
<pre><code>df = pd.DataFrame(np.random.randn(10).reshape(5,2), index =['a','b','c','d','e'], columns = ['one', 'two']) convert_decimal = lambda x: '{:.1f}'.format(x) df = df.applymap(convert_decimal) df </code></pre> <blockquote> <p>Error: TypeError Traceback (most recent call last) in ----> 1 abs(df)</p> ...
<p>It looks like you could just cast the lambda computation as a float.</p>
python|pandas
0
354,323
61,330,819
How to add additional arguments to map(pd_read_csv)?
<p>About 2 years ago someone had a very elegant way of reading multiple csv files into one dataframe: <a href="https://stackoverflow.com/questions/20906474/import-multiple-csv-files-into-pandas-and-concatenate-into-one-dataframe">Import multiple csv files into pandas and concatenate into one DataFrame</a></p> <pre><co...
<p>You can use <em>itertools.starmap</em>.</p> <p>This function takes:</p> <ul> <li>a function as the first argument,</li> <li>and runs it on each set of parameters from an iterable (second argument - a list of tuples).</li> </ul> <p>I ran the following example:</p> <pre><code>import itertools as it # read_csv wra...
python|pandas|csv|concatenation
0
354,324
61,249,487
how to drop duplicates after merging two dataframes?
<p>I have two dataframes ,</p> <pre><code>A= ID compponent weight 12 Cap 0.4 12 Pump 183 12 label 0.05 14 cap 0.6 B= ID compponent_B weight_B 12 Cap_B 0.7 12 Pump_B 189 12 label 0.05 </code></pre> <p>when i do merge of this two dataframes based on the ID as a key ...
<p>you can create a column with a <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow noreferrer"><code>cumcount</code></a> per ID to be able to <code>merge</code> on ID and this new column so like:</p> <pre><code>dfm = dfA.assign(cc=dfA.groupby(...
python|pandas|dataframe|merge|drop-duplicates
1
354,325
61,502,603
Import Tensorflow without NVIDIA GPU (ImportError: Could not find 'nvcuda.dll')
<p>I have installed the <code>tensorflow</code> package using Anaconda Navigator. When I try to run <code>import tensorflow</code> in a jupyter notebook I get the following error:</p> <pre><code> OSError Traceback (most recent call last) D:\ProgrammFiles\Anaconda\lib\site-packages\t...
<p>As discussed in the comments, the problem was only in your installation. Using anaconda-navigator isn't the best way to install <code>tensorflow</code>. My assumption is either <code>tensorflow-base</code> or <code>tensorflow-estimate</code> has a GPU dependency which is the reason why it kept showing the posted err...
python|tensorflow|anaconda
1
354,326
61,359,162
Convert a list of tensors to tensors of tensors pytorch
<p>I have this code:</p> <pre class="lang-py prettyprint-override"><code>import torch list_of_tensors = [ torch.randn(3), torch.randn(3), torch.randn(3)] tensor_of_tensors = torch.tensor(list_of_tensors) </code></pre> <p>I am getting the error:</p> <blockquote> <p>ValueError: only one element tensors can be conve...
<p>Here is a solution:</p> <pre><code>tensor_of_tensors = torch.stack((list_of_tensors)) print(tensor_of_tensors) #shape (3,3) </code></pre>
python|python-3.x|pytorch
9
354,327
61,557,367
Vectorized extraction of submatrices in numpy-array
<p>My goal is to implement a median-filter, which is a function, that replaces each pixel in a (mostly) 2d-array with the median of its surrounding pixels. It can be used to denoise images.</p> <p>My implementation extracts submatrices from the original matrix, that contain the pixel itself and its neighbors. This ext...
<p>Here is a vectorized solution. However, you can come up with a faster solution by paying attention to memory order of the image array:</p> <pre><code>from numpy.lib.stride_tricks import as_strided img_padded = np.pad(img, 1, mode='constant') sub_shape = (fsize, fsize) view_shape = tuple(np.subtract(img_padded.shap...
python|numpy|image-processing|computer-vision|vectorization
3
354,328
61,467,671
Finding occurances by comparing 2 columns in dataframe
<p>This is my dataframe:</p> <pre><code>d = {'id':[1,2,3,4,5,6,7,8], 'col1':['A','A','A','B','B','B','C','D'], 'col2':['C','C','D', 'E', 'F', 'F','G','H'], 'data':['abc','def','ghk','lmn','opq','rst','uvw','xyz'] } df = pd.DataFrame(d) </code></pre> <p>I want to find all values in col2 for each unique ...
<p>If you insist on getting exactly that output, here's one way:</p> <pre><code>df = df.drop_duplicates(subset=[ 'col1', 'col2' ]).drop('id', axis=1).reset_index(drop=True) df['col1'] = np.where(df.col1.duplicated()==True, '', df.col1) </code></pre> <p>Which produces: </p> <pre><code> col1 col2 0 A ...
pandas
1
354,329
61,310,920
Counting number of consecutive more than 2 occurences
<p>I am beginner, and I really need help on the following:</p> <p>I need to do similar to the following but on a two dimensional dataframe <a href="https://stackoverflow.com/questions/37934399/identifying-consecutive-occurrences-of-a-value/61310753#61310753">Identifying consecutive occurrences of a value</a> </p> <p...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df=pd.DataFrame({0:[1,0,1,0,0,1,1,1], 1:[0,1,1,0,1,1,1,0], 2: [1,0,1,1,0,0,1,1]}) out_2_df=((df.diff(axis=0).eq(0)|df.diff(periods=-1,axis=0).eq(0))&amp;df.eq(1)).sum(axis=0) &gt;&gt;&gt; out_2_df [3 5 4] </code></pre>
python|pandas|dataframe
1
354,330
68,731,821
How to sample data from Pandas Dataframe based on value count from another column
<p>I have a dataframe of about 400,000 observations. I want to sample 50,000 observations based on the amount of each state that's in a 'state' column. So if there is 5% of all observations from TX, then 2,500 of the samples should be from TX, and so on.</p> <p>I tried the following:</p> <pre><code>import pandas as p...
<p>Weights modify the probability of any one row to be selected, but can’t provide strict guarantees on counts of given values, as you want. For that you would need <code>.groupby('state')</code>:</p> <pre><code>&gt;&gt;&gt; rate = df['state'].value_counts(normalize=True) &gt;&gt;&gt; rate TX 0.5 NY 0.3 CA 0.2...
python|pandas|sample
3
354,331
68,469,118
Appropriate concat for dataframes of different size
<p>I have some dataframes of different row size (columns are the same) and I want to calculate the sum of each column in the last row and then combine them in one dataframe.</p> <p>I'm using this function:</p> <pre><code>def day_sum(tot_df): week_days = ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU', 'Total'] week = [] for...
<p>Instead of your code just use:</p> <pre><code>df.loc[len(df)] = ['sum'] + df[df.columns[1:]].sum(0).tolist() </code></pre>
python|pandas
0
354,332
68,767,795
Adding timestamps to pandas series
<p>I'm trying to write a code that will count a number of records in a .csv file in a single hour. So, for example:</p> <pre><code> data = pd.read_csv('2021-07-30.csv', parse_dates=['time'], infer_datetime_format=True) datafiltr = data[data.lane == &quot;Lane 4 Op2&quot;] datafiltr['time'] = pd.to_datetime(dat...
<p>have you tried with resampling, but at least one of your time sample should be of max time to consider till there</p> <pre><code>df.set_index('time').resample('H').agg('count') </code></pre> <p>out:</p> <pre><code> 1 2 0 2021-08-13 13:00:00 1 1 2021-08-13 14:00:00 1 1 2021-08-13 15:00:00 1 1 2021-0...
python|pandas|csv|matplotlib
0
354,333
68,556,051
Fast Style Transfer tensorflow Python
<p>I follow this link to try machine learning - real time Fast Style Transfer <a href="https://www.youtube.com/watch?v=LWlbFVtPiwo&amp;ab_channel=CODEMENTAL" rel="nofollow noreferrer">https://www.youtube.com/watch?v=LWlbFVtPiwo&amp;ab_channel=CODEMENTAL</a>.</p> <p>However, in my python it shows GPU available: False D...
<p>GPU is recommended in computation intensive deep learning problems and you need both &quot;Source&quot; and &quot;Style&quot; image either in cloud or local storage to get a Fast Style transfer image.Attaching <a href="https://www.tensorflow.org/hub/tutorials/tf2_arbitrary_image_stylization" rel="nofollow noreferr...
python|tensorflow|jupyter-notebook
0
354,334
68,601,912
Fastest way to append a row to an existing data frame?
<p>I know this question has been asked many a time, but none of the solutions already posted on this site is ideal.</p> <p>I have tested various methods found here, and timed them using IPython, I will post the results below:</p> <pre class="lang-py prettyprint-override"><code>In [161]: %%timeit ...: s = Series([1...
<p>First we establish the time needed to create a dataframe:</p> <pre><code>%%timeit songs = pd.DataFrame(index=np.arange(4464 ), columns=np.arange(15)) 100 loops, best of 5: 5.21 ms per loop </code></pre> <p>It takes around 5.2 ms to create this dataframe and so we can use it as a reference for the next cases (to pre...
python|python-3.x|pandas|dataframe
0
354,335
68,771,454
Split dataframe based on a continuous column value, not present in the dataframe
<p>I am trying to split a dataframe into several ones based on a list with the splitting points or threshold, which don't necessarily need to be in the reference column. I haven't quite found an answer for this</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Values</th> <th>Another header</...
<p>Another looping option</p> <pre><code>thresholds = [4,10] thresholds = [float('-inf')] + thresholds + [float('inf')] empty = [] for i in range(len(thresholds)-1): t_start = thresholds[i] t_end = thresholds[i+1] temp = df.query('Values &gt; @t_start &amp; Values &lt;= @t_end') empty.append(temp) ...
python|pandas
1
354,336
68,868,881
Match two separate dataframes to a larger dataframe based on matching values (In Python)
<p>I have 1 large dataframe, and 2 smaller dataframes in which I would like to append/match based on certain criteria.</p> <p><strong>Data</strong></p> <p><em>df1</em> (large dataframe)</p> <pre><code>id Date pp pos aa q122 200 10 aa q222 200 10 bb q322 500 5 bb q422 500 5 cc q122 100 2 cc q22...
<p>We can chain <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html" rel="nofollow noreferrer"><code>merge</code></a> operations:</p> <pre><code>out = ( df1.merge( df2, left_on=['id', 'Date'], right_on=['name', 'date1'], how='outer' ).merge( df3, left_on=['id', 'Dat...
python|pandas|numpy
2
354,337
68,484,274
Pandas: Get matched value between two columns
<p>I have <strong>2 dataframes</strong></p> <pre><code>data1 = {'Product': ['AAA','BBB','CCC','DDD','EEE','FFF'], 'Id': ['247610','287950','229XYZ','987340','111500','2345OZ'], 'Price':[40,50,0,985,34,0]} data2 = {'Product': ['AAA','BBB','CCC','DDD','EEE'], 'Id': [508760,287950,678897,987340,11...
<p>It's easier to convert your 'Id' of df2 from int to str:</p> <pre><code>df2 = pd.DataFrame(data2).astype({'Id': str}) df1['bestId'] = df1[&quot;Id&quot;].isin(df2[&quot;Id&quot;]) </code></pre> <pre><code>&gt;&gt;&gt; df1 Product Id Price bestId 0 AAA 247610 40 False 1 BBB 287950 50 ...
python|pandas|dataframe
1
354,338
68,751,253
How to keep leading zeros in a column when reading JSONwith Pandas?
<pre><code>total_list = ['123456','00123456'] df = pd.read_json(json.dumps(total_list)) print(df) </code></pre> <p>The result is:</p> <pre><code> 0 0 123456 1 123456 </code></pre> <p>But I want to keep the '0',how can I do this?</p>
<p>Use <code>dtype == str</code>:</p> <pre><code>total_list = ['123456','00123456'] df = pd.read_json(json.dumps(total_list), dtype=str) print(df) </code></pre> <p>Output:</p> <pre><code> 0 0 123456 1 00123456 </code></pre>
python|json|pandas|dataframe
0
354,339
68,764,677
Extract HTML information from df variable
<p>Dear stackoverflow community,</p> <p>This is my first time asking a question here. Hope you could cut me some slack. Here is the description of a problem:</p> <ol> <li>I convert KML file to CSV using ogr2org <br /> <code>ogr2ogr -f CSV output.csv 'some KML file'.kml</code></li> <li>I then read in the csv file in pan...
<p>You could use <code>str.extractall</code> with...</p> <pre><code>df[['ID1', 'class', 'fold']] = df['description'].str.extractall(r'&lt;/b&gt;\s?(\d+)&lt;').unstack() </code></pre> <p>Or <code>str.findall</code> with something like this...</p> <pre><code>df[['ID1', 'class', 'fold']] = df['description'].str.findall(r'...
html|pandas|kml
1
354,340
68,809,809
returning scikit-learn object while using Joblib
<p>I have a numpy array, and I am using sklearn to transform the array along the first axis. I also want to save the transformer object in a dict to use later in the code. Here is my code:</p> <pre><code>scalers_dict = {} for i in range(train_data_numpy.shape[1]): for j in range(train_data_numpy.shape[2]): ...
<p>You can use <a href="https://docs.dask.org/en/latest/" rel="nofollow noreferrer">Dask-ML</a> which is implemented on the top of <a href="https://dask.org/" rel="nofollow noreferrer">Dask Library</a>, yet it is compatible with <code>scikit-learn</code>.</p> <p><a href="https://ml.dask.org/install.html?#installation" ...
python|scikit-learn|parallel-processing|numpy-ndarray|joblib
1
354,341
68,486,056
Different behavior while reading DataFrame from parquet using CLI Versus executable on same environment
<p>Please consider following program as <a href="https://stackoverflow.com/help/minimal-reproducible-example">Minimal Reproducible Example -MRE</a>:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import pyarrow from pyarrow import parquet def foo(): print(pyarrow.__file__) print('versi...
<p>Credit to @U12-Forward for assisting me in debugging the issue.</p> <p>After a bit of research and debugging, and exploring the library program files, I found that pyarrow uses <code>_ParquetDatasetV2</code> and <code>ParquetDataset</code> functions which are essentially two different functions that reads the data f...
python|pandas|pyinstaller|parquet|pyarrow
3
354,342
68,646,855
How to ensure that my model is using all available GPU in jupyter notebook
<p>I am using <code>tensorflow 2.3</code> dedicated with <code>2-GPU's</code>. I am using <code>styleformer</code> model to get informal to formal sentences. I want to use all <code>2-GPU's</code> for this task.</p> <p><strong>Here is the information about GPU:</strong></p> <pre><code>!nvidia-smi | NVIDIA-SMI XXX.XX.X...
<p>your model is not using the GPU, there could be multiple reasons,</p> <ol> <li>you did not install the Cuda toolkit &amp; drivers for the GPU to access in the developer mode</li> <li>Nvidia Driver issue ( uninstall &amp; install)</li> <li>Tensorflow version issue</li> </ol> <p>check all these and try again. The note...
python-3.x|tensorflow|jupyter-notebook|nvidia
0
354,343
68,731,152
How to create a heatmap to display matching and not matching data
<p>I have some parcel data that shows which city the volume of parcels belongs to.</p> <pre><code>+---------+-------------+----------------+ | Volume | City | Foreign_City | +---------+-------------+----------------+ | 200 | Chicago | New York | | 300 | Los Angeles | NaN | | 1...
<ul> <li>Given the existing data, when there's a match between <code>'City'</code> and <code>'Foreign_City'</code>, there are three options depending on your desired plot. <ol> <li>Use <code>.fillna</code> in <code>'Foreign_City'</code> with the corresponding row from <code>'City'</code>. <ul> <li>The heatmap will have...
python|pandas|matplotlib|plot|seaborn
1
354,344
68,782,958
Changing width of particular column in Dataframe
<p>I have pandas Dataframe with 10-11 Columns. I want to convert this dataframe into html using pd.to_html(index=False, border=0). However, I want to change CSS of returned table. Can we change column width of dataframe itself, or format tags of returned table from pd.to_html()</p> <p>Html Code for expected table</p> ...
<p>You can use the styler of df:</p> <pre><code>df_html = df.style.set_table_styles({ 'A': [{'selector': 'thead tr', 'props': [('width', '5%')]}], 'D': [{'selector': 'thead tr', 'props': [('width', '3%')]}], }) print(df_html.render(sparse_index=True)) </code></pre> <p>The output is pretty...
html|css|pandas|dataframe
0
354,345
68,611,026
Loss of Image Information
<p>When reading a JPEG image from a <a href="https://www.tensorflow.org/tutorials/load_data/tfrecord" rel="nofollow noreferrer">TFRecord</a> there seems to be loss of information. Here is an example:</p> <ul> <li>Original image: <a href="https://i.stack.imgur.com/QyKMI.jpg" rel="nofollow noreferrer">https://i.stack.img...
<p>What do you mean by &quot;loss of image informatIon&quot;? I actually found out tf.io.encode_jpeg and tf.io.decode_jpeg op (using all their defaults), are not necessary symmetrical, meaning if you apply decode follow by encode, the image jpeg can have a different byte count. If you encode_jpeg with high quality=100,...
python|tensorflow|machine-learning|keras|tfrecord
0
354,346
68,596,129
Iterate each Pandas df row and identify if row value is in list, if so pull that value into df
<p>I have a pandas df with hand entered values for states around the world. I have a list of states values that are properly formatted and contain the correct syntax. I want to iterate through each row in the pandas df and compare the value per row against all values in the list of states to determine whether the value...
<p>Try the following:</p> <pre><code>s = set([i.lower() for i in states_list]) df['match'] = df['state_name'].apply(lambda x: list(set([i.strip().lower() for i in x.split(',')]).intersection( s))) df['match']=df['match'].apply(lambda x: [i[0].upper() + i[1:] for i in x]) </code></pre>
python|pandas|dataframe|contains|difflib
1
354,347
68,648,581
Getting wrong results with np.argpartition, while selecting maximum n values from an array
<p>so I was using <a href="https://stackoverflow.com/a/23734295/12705907">this</a> answer on 'How do I get indices of N maximum values in a NumPy array?' question. I used it in my ML model in which it outputs Logsoftmax layer values and I was thinking to get top 4 classes in each. In most of the cases, it sorted and ga...
<p>If you're not planning on actually utilizing the sorted indices, why not just use <a href="https://numpy.org/doc/stable/reference/generated/numpy.sort.html" rel="nofollow noreferrer"><code>np.sort</code></a>?</p> <pre><code>&gt;&gt;&gt; arr = np.array([-3.0302, -2.7103, -7.4844, -3.4761, -5.3009, -5.2121, -3.7549, ...
python|arrays|numpy|sorting|numpy-slicing
1
354,348
68,487,967
Inserting rows in df based on groupby using value of previous row
<p>I need to insert rows based on the column week based on the groupby type, in some cases i have missing weeks in the middle of the dataframe at different positions and i want to insert rows to fill in the missing rows as copies of the last existing row, in this case copies of week 7 to fill in the weeks 8 and 9 and c...
<p>For the first part of your question. Suppose we have a dataframe like the following:</p> <pre><code>df = DataFrame({&quot;project&quot;:[1,1,1,2,2,2], &quot;week&quot;:[1,3,4,1,2,4], &quot;value&quot;:[12,22,18,17,18,23]}) </code></pre> <p>We can create a new multi index to get the additional rows that we need</p> <...
python|pandas|dataframe|missing-data
1
354,349
68,604,186
Convert 3D RGB np array to 2D binary
<p>I am currently trying to find an efficient way of taking an RGB image and converting it to a binary/ black and white image. To the likes of:</p> <pre><code>RGBnp = [ [[255, 255, 255], [0 , 0 , 0 ], [0 , 0 , 0 ]], [[255, 255, 255], [255, 255, 255], [255, 255, 255]], [[255, 255, 255...
<p>Here you go:</p> <pre><code>RGBnp = np.array(RGBnp) RGBnp[RGBnp == 255] = 1 BinaryNP = RGBnp[:,:,0] </code></pre>
python|numpy|matrix
2
354,350
68,581,545
Scatter Plot With Multi Column Data in Plotly Express
<p>I have a <code>pandas</code> dataframe like below</p> <pre><code> x s y Date 2021-06-25 1 red 2 2021-06-28 2 red 3 2021-06-29 3 red 4 2021-06-25 1 blue 2 2021-06-28 2 blue 3 2021-06-29 3 blue 4 </code></pre> <p>How can I cre...
<ul> <li>your sample data looks problematic, both red and blue have same values. Have added .5 to blue to demonstrate</li> <li>simple <strong>pandas</strong> to structure data first, so colors are columns</li> <li>then use <strong>plotly express</strong> <code>scatter()</code></li> </ul> <pre><code>import pandas as pd...
pandas|dataframe|plotly
1
354,351
68,747,545
How to calculate cumulative percent change by each group?
<p>I'd like to create a new column to calculate the cumulative percent change by each group</p> <p>Sample dataset:</p> <pre><code>import pandas as pd df = pd.DataFrame({'Group':['A', 'A', 'A', 'B', 'B'], 'Col_1':[100, 200, 300, 400, 500], 'Col_2':[55, 66, 77, 88, 99]}) </cod...
<p>You need to <code>groupby</code> twice, once to compute the percent change (with <code>pct_change</code>) and once for the cumulative sum+1 (<code>cumsum</code> and <code>add(1)</code>):</p> <pre><code>df['CPC'] = (df.groupby('Group')['Col_2'] .pct_change() .fillna(0) .gr...
pandas|dataframe|group-by
1
354,352
68,778,058
Pandas Dataframe Subtract Value From Previous Rows Based On Condition
<p>I have the following Pandas dataframe:</p> <p><strong>UPDATE:</strong></p> <p><strong>I slightly changed the example (Last row) to make the output clearer for @mozway</strong></p> <pre><code> value initial_quantity updated_quantity date 2021-09-01 50 100 100 2021-10-01 50 ...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/version/0.23/generated/pandas.Series.cumsum.html" rel="nofollow noreferrer"><code>cumsum</code></a> + <a href="https://pandas.pydata.org/pandas-docs/version/1.0.3/reference/api/pandas.Series.clip.html" rel="nofollow noreferrer"><code>clip</code></a>:</p> <pr...
python|pandas|dataframe
1
354,353
68,790,771
AttributeError: module 'tensorflow.compat.v2' has no attribute 'depth_to_space'
<p>I am trying to run a code, which was written with tensorflow version 1.4.0 I am running my code on google colab which gives in tensorflow version 2.x with it.</p> <p>To run my code, I am using backward compatibility like: replacing <code>import tensorflow as tf</code> with</p> <pre><code>import tensorflow.compat.v1 ...
<p>I tried with <strong>Tensorflow 1.15</strong>.Its working fine. Looks like your Tensorflow version bit old,</p> <p>Below sample code tested with Tf 1.15 without any error.</p> <pre><code>import tensorflow as tf print(tf.__version__) x = [[[[1, 2, 3, 4]]]] tf.nn.depth_to_space(x, 2, data_format='NHWC', name=None) </...
python|tensorflow|tensorflow1.15
0
354,354
68,485,692
Copy rows from one dataframe to another dataframe for specific matched rows
<p>I have a dataframe <code>df1</code> like the following:</p> <pre><code>ID Name Test1 100 Ben 30 111 Mark 40 122 Dave 25 </code></pre> <p>and another dataframe <code>df2</code> like the following:</p> <pre><code>ID Test2 Test3 100 22 ...
<p>You want <code>pandas.merge</code>:</p> <pre><code>&gt;&gt;&gt; pd.merge(df1, df2, on=&quot;ID&quot;, how=&quot;left&quot;) ID Name Test1 Test2 Test3 0 100 Ben 30 22.0 29.0 1 111 Mark 40 NaN NaN 2 122 Dave 25 37.0 34.0 </code></pre>
python|pandas|dataframe
1
354,355
68,553,853
if df.A=0 & df.b=1 then df.c=1/ pandas python
<p>df:</p> <pre><code>A B 0 1 1 1 0 0 </code></pre> <p><strong>Aim</strong>: if df.A=0 &amp; df.B=1 then create a column C=1 else return nothing. The result should be: df:</p> <pre><code>A B C 0 1 1 1 1 0 0 0 1 1 </code></pre> <p>My current code gives this error: &quot;ValueError: The truth value of a DataF...
<p>Try:</p> <pre><code>m=(df['A'].eq(0)) &amp; (df['B'].eq(1)) #Finally: df['C'] =m.astype(int).replace(0,'') </code></pre> <p>OR</p> <pre><code>#import numpy as np m=(df['A'].eq(0)) &amp; (df['B'].eq(1)) df['C']=np.where(m,1,'') </code></pre> <p>OR</p> <p>For your current method use bitwise <code>&amp;</code> and <cod...
python|pandas|dataframe
1
354,356
68,818,383
pip install pandas conflict with Pylance
<p>&quot;pip is not defined&quot; &quot;install is not defined&quot; &quot;pandas is not defined&quot;</p> <p>I'm trying to install pandas into VSCode since I received a &quot;ModuleNotFoundError&quot; from trying to import pandas in the first place.</p> <p><img src="https://i.stack.imgur.com/xhLGo.png" alt="" /></p>
<p>So i do not have the knowledge to go in the details to explain why pip is particular but pip is an executable so you have to execute it in a terminal. to install pandas (or any other module from pyPI like sklearn, seaborn, time and many others) follow the instruction (it works for me):</p> <ul> <li>go on VScode and ...
python|pandas|visual-studio-code|pip
0
354,357
68,864,520
Pandas: Cell frequency count by index
<p>My dataframe is a long list of 4 letters, <code>'A', 'T', 'G','C'</code>, I need to count the frequency of each letter by index</p> <pre><code>df = pd.DataFrame({'cases': ['ACCTTGTAGTGTATTTTATGACCAAATGACTTTTTCCCCCCAGTGGCTAATTTGTCTCAGGCCTGCGTCTTAAAGAGACACGGTAATGAGTAGGAAGTCCAGCGTGGTCTGGA','ACCTTGTACTGTATCTTATGACCAGATG...
<p>Let us do <code>explode</code> with <code>crosstab</code></p> <pre><code>s = df.cases.map(list).explode() out = pd.crosstab(s.groupby(level=0).cumcount(),s) Out[583]: cases A C G T row_0 0 3 0 1 0 1 0 4 0 0 2 0 4 0 0 3 0 0 0 4 4 0 0 0 4 .. .. .. .. 108 0...
python|pandas|dataframe
6
354,358
68,795,120
What's an alternative way to wright a nested for loop instead of single line for loop below? I have been getting index errors on my current solution
<p><img src="https://i.stack.imgur.com/eos7j.jpg" alt="example question" /></p> <pre><code>import sys import numpy as np myarray=[] for j in range(3): myarray.append(j) for i in range (3): myarray[i]=i+j print(myarray) </code></pre>
<p>The key thing to understand is you are creating nested lists here. You need to create an intermediate list on each outer iteration to append to the final list.</p> <pre><code>&gt;&gt;&gt; result = [] &gt;&gt;&gt; for j in range(3): ... intermediate = [] ... for i in range(3): ... intermediate.append(...
python|numpy
-1
354,359
68,492,035
Python Parallelise Simple For Loop
<p>I am trying to make the code below run faster. In its current state, it is taking around 5-6 minutes, which is a lot for the occasion. I am working on two pandas dataframes, taking a datetime and an 'instrument' from the <code>rfqs</code> dataframe, matching the instrument on the second dataframe and finding the clo...
<p>Letting Pandas do its magic by formulating the problem at a higher level of abstraction may already yield the speed-up you're looking for. I'd create a new column <code>nearest_date</code> in <code>rfqs</code>, e.g.</p> <pre><code>mids = mids.set_index(&quot;instrument&quot;) # faster lookup rfqs['nearest_date'] = r...
python|pandas|numpy|parallel-processing
0
354,360
68,774,902
Pandas Date Conversion from "23-Oct-2020; 27-Aug-2020" to "10/23/2020; 8/27/2020"
<p>I received data from an external source that has time stamps in DDMMMYYYY format and want to convert it to MM/DD/YYYY format. Can you think of a way to do this?</p> <p>Input 23-Oct-2020 27-Aug-2020 04-Dec-2019</p> <p>Output that i am looking to get 10/23/2020 8/27/2020 12/04/2019</p>
<p>Like this:</p> <pre><code>df['date'] = pd.to_datetime(df['date'], format='%d-%b-%Y') </code></pre>
python-3.x|pandas|dataframe
1
354,361
68,523,348
How to apply statististical tests (functions) on pandas dataframe on combination of subsets of data
<p>I have dataframe which is similar to this one.</p> <pre><code>import pandas as pd import string import random def generate_example_dataframe()-&gt; pd.DataFrame: &quot;&quot;&quot; This simple function will generate simple dataframe in long format &quot;&quot;&quot; num = 20 # number of regions udsed...
<p>im also learn other methods from others' answers. i made a solution like this below...</p> <pre><code># grouping df['grouping']=df['region']+&quot;_&quot;+df['group']+&quot;_&quot;+df['condition'] for i in df.grouping.unique(): print(i) t='result_'+i locals()[t]=stats.ttest_1samp(df.loc[df['grouping']=...
python|pandas|pandas-groupby|statistical-test
0
354,362
68,560,005
numpy broadcast multiply on condition?
<p>I have two arrays, one of shape <code>arr1.shape = (1000,2)</code> and the other of shape <code>arr2.shape = (100,)</code>.</p> <p>I'd like to somehow multiply <code>arr1[:,1]*arr2</code> where <code>arr1[:,0] == arr2.index</code> so that I get a final shape of <code>arr_out.shape = (1000,)</code>. The first column ...
<p>I believe this does exactly what you want:</p> <pre><code>indices, values = arr1[:,0].astype(int), arr1[:,1] arr_out = values * arr2[indices] </code></pre>
python|arrays|numpy
2
354,363
68,791,512
Pandas to_numeric unable to turn decimal data from db2 into float64
<p>The process is as below:</p> <ol> <li><p>Script retrieve a column from a data in IBM DB2. The data is of data type = &quot;Decimal&quot;</p> </li> <li><p>after retrieval, the queries is store in a variable called&quot;result&quot; and being casted into a dataframe column &quot;loading&quot;. dtype indicates the data...
<p>This is because you still have parantheses. Remove them then convert:</p> <pre><code>Tuen_Mun_Weather_2013[&quot;Loading&quot;] = Tuen_Mun_Weather_2013.Loading.str.replace('\(|\)','').astype('float64') </code></pre>
python|pandas|db2
1
354,364
68,481,158
Which Java class is compatible with python Pandas DataFrame when using DJL(Deep Java Library)?
<p>I'm trying to import Python Tensorflow custom model to <code>spring-boot</code> using <code>DJL Tensorflow</code>, and the model gets <code>Pandas DataFrame</code> as both input and output.</p> <p>I'm wondering if there is any particular table or dataFrame class that is applicable for Criteria&lt;I, O&gt; and ZooMod...
<p>You need create your own <code>Translator</code> to convert <code>DataFrame</code> into <code>NDList</code>:</p> <pre><code> class MyTranslator implements NoBatchifyTranslator&lt;DataFrame, Classifcations&gt; { @Override public NDList processInput(TranslatorContext ctx, DataFrame input) { ...
java|pandas|spring-boot|dataframe|djl
0
354,365
68,704,002
ImportError: cannot import name 'ABCIndexClass' from 'pandas.core.dtypes.generic'
<p>I have this output :</p> <blockquote> <p>[Pandas-profiling] ImportError: cannot import name 'ABCIndexClass' from 'pandas.core.dtypes.generic'</p> </blockquote> <p>when trying to import pandas-profiling in this fashion :</p> <pre class="lang-py prettyprint-override"><code>from pandas_profiling import ProfileReport </...
<p>Pandas v1.3 renamed the <code>ABCIndexClass</code> to <code>ABCIndex</code>. The <code>visions</code> dependency of the <code>pandas-profiling</code> package hasn't caught up yet, and so throws an error when it can't find <code>ABCIndexClass</code>. Downgrading pandas to the 1.2.x series will resolve the issue.</p>...
python|pandas|pandas-profiling
18
354,366
68,608,741
Numpy array with different data types
<p>We both know that: &quot;Numpy array is multidimensional array of objects of all the same type&quot;</p> <p>However, I could create a Numpy array that contains different data types as example below. Can anyone give an explain, how it could be.</p> <pre><code>import numpy as np a = np.array([('a',1),('b',2)],dtype=[...
<p>Those are numpy records:</p> <ul> <li><a href="https://numpy.org/doc/stable/user/basics.rec.html" rel="nofollow noreferrer">https://numpy.org/doc/stable/user/basics.rec.html</a></li> </ul> <p>Numpy provides two data structures, the homogeneous arrays and the structured (aka <em>record</em>) arrays. The latter one, w...
python|numpy|multidimensional-array
3
354,367
68,605,299
ValueError: Cannot convert non-finite values (NA or inf) to integer
<pre><code>df.dtypes name object rating object genre object year int64 released object score float64 votes float64 director object writer object star object country object budget float64 gross float64 company object runtime float64...
<p>Assuming that the budget does not contain infinite values, the problem may be because you have nan values. These values are usually allowed in floats but not in ints.</p> <p>You can:</p> <ol> <li>Drop na values before converting</li> <li>Or, if you still want the na values and have a recent version of pandas, you ca...
python|pandas|numpy
8
354,368
68,471,066
Set individual wedge hatching for pandas pie chart
<p>I am trying to make pie charts where some of the wedges have hatching and some of them don't, based on their content. The data consists of questions and yes/no/in progress answers, as shown below in the MWE.</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt raw_data = {'Q1': ['IP', 'IP', 'Y/IP', 'Y...
<p>This snippet shows how to add hatching in custom colors to a pie chart. You can extract the Pandas valuecount - this will be a <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.html" rel="nofollow noreferrer">Series</a> - then use it with the snippet I have provided.</p> <p>I have add...
python|python-3.x|pandas|matplotlib
1
354,369
68,593,293
Performance tuning: string wordcount in df
<p>I have a df with column &quot;free text&quot;. I wish to count how many characters and words each cell has. Currently, I do it like this:</p> <pre><code>d = {'free text': [&quot;merry had a little lamb&quot;, &quot;Little Jonathan found a chicken&quot;]} df = pd.DataFrame(data=d) df['Chars'] = df['free text'].apply(...
<p>IIUC:</p> <p>you can try via <code>str.len()</code> and <code>str.count()</code>:</p> <pre><code>df['Chars'] = df['free text'].str.len() df['Words'] = df['free text'].str.count(' ')+1 </code></pre> <p>Sample dataframe used:</p> <pre><code>d = {'free text': [&quot;merry had a little lamb&quot;, &quot;Little Jonathan ...
python|pandas|performance
1
354,370
68,661,587
.loc function for a specific label returning an empty data frame?
<p>For context, I'm trying to filter out rows in my dataframe that only belong to the year 2021.</p> <p>This is my script code:</p> <p><code>test = all_SS_batting_columns.loc[all_SS_batting_columns['Year'] == '2021']</code></p> <p>but it only returns:</p> <pre><code>Empty DataFrame Columns: [index, Year, Age, Tm, Lg, G...
<p>Duplicate df name to see all columns:</p> <pre><code> test = all_SS_batting_columns[all_SS_batting_columns.loc[all_SS_batting_columns['Year'] == '2021']] </code></pre>
python|pandas|filter|.loc
0
354,371
68,782,961
How to know a movie has how many 0.5/1/1.5/2/2.5/3/3.5/4/4.5/5 rating that rated by every user?
<p>I would like to know how many 0.5/1/1.5/2/2.5/3/3.5/4/4.5/5 ratings that rated by every user in a data frame of a certain movie which is Ocean's Eleven (2001) in order to calculate Pearson Correlation using the formula.</p> <p><strong>Below is the code</strong></p> <pre><code>import numpy as np import pandas as pd ...
<p>You can use <code>groupby</code>:</p> <pre><code>oceanRatings = matrix_user_ratings[&quot;Ocean's Eleven (2001)&quot;].groupby('rating').count() </code></pre> <p>Or <code>value_counts()</code>:</p> <pre><code>oceanRatings = matrix_user_ratings[&quot;Ocean's Eleven (2001)&quot;].value_counts() </code></pre>
python|pandas|dataframe
0
354,372
68,857,527
Object Detection with TensorFlow 2 : ImportError: cannot import name 'anchor_generator_pb2' from 'object_detection.protos'
<p>I am trying to train a model using Tensorflow 2 as written here: <a href="https://colab.research.google.com/drive/1sLqFKVV94wm-lglFq_0kGo2ciM0kecWD#scrollTo=fF8ysCfYKgTP&amp;uniqifier=1" rel="nofollow noreferrer">https://colab.research.google.com/drive/1sLqFKVV94wm-lglFq_0kGo2ciM0kecWD#scrollTo=fF8ysCfYKgTP&amp;uniq...
<p>I solved the problem. It turned out that python was trying to import files from a different directory. I moved the project to this folder and it worked.</p> <p>I spent 2 days solving this problem. If anyone has the same problem, take a close look at where the import fails.</p>
python|tensorflow
0
354,373
68,643,845
Pandas conditional formatting: Highlighting cells in one frame that are unequal to those in another
<p>Given two pandas dataframes df1 and df2 that have exact same schema (i.e. same index and columns, and hence equal size), I want to color just those cells in df1 that are unequal to their counterpart in df2. Any hints?</p> <p>More generally, if I have a predefined matrix of colors, colormat, that has the same dimensi...
<p>The styles need to be valid CSS, so change 'red' and 'green' to <code>'background-color: red'</code> and <code>'background-color: green'</code>, then simply <a href="https://pandas.pydata.org/docs/reference/api/pandas.io.formats.style.Styler.apply.html" rel="nofollow noreferrer"><code>apply</code></a> on <code>axis=...
python|pandas|pandas-styles|python-applymap
0
354,374
68,532,200
Creating a Pandas DataFrame from a NumPy masked array?
<p>I am trying to create a Pandas <code>DataFrame</code> from a NumPy masked array, which I understand is a supported operation. This is an example of the source array:</p> <pre class="lang-py prettyprint-override"><code>a = ma.array([(1, 2.2), (42, 5.5)], dtype=[('a',int),('b',float)], mask=[...
<p>If the array has a simple dtype, the dataframe creation works (as documented):</p> <pre><code>In [320]: a = np.ma.array([(1, 2.2), (42, 5.5)], ...: mask=[(True,False),(False,True)]) In [321]: a Out[321]: masked_array( data=[[--, 2.2], [42.0, --]], mask=[[ True, False], [False, True]], ...
pandas|numpy|missing-data
3
354,375
68,848,067
Fuzzy matching only for values within same group
<p>I am stuck with this problem that should have a simple solution but I cannot find it.</p> <p>I have two data frames:</p> <p>dfA</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Company</th> <th>Country Code</th> </tr> </thead> <tbody> <tr> <td>CompanyA</td> <td>IT</td> </tr> <tr> <td>Comp...
<p>Build a a restrictive list where to apply the process. Use <code>extractOne(...)</code> instead of <code>extract(...)[0]</code> to get only one value.</p> <pre><code>dfA['Company List'] = pd.merge(dfA, dfB, on='Country Code', how='left') \ .groupby('Company_x')['Company_y'] \ ...
python|pandas|fuzzywuzzy
0
354,376
68,503,155
Shortest path from A to B in a weighted and directed 2D pandas csv graph
<p>I have a weighted graph represented by 2D n x n matrix that I created using pandas and saved as a csv file</p> <p>The indices and column headers are numbers that represent the nodes. the edges are weights connecting two nodes</p> <p>for example: {1232: {1232: inf, 2342: 12, 45654: inf, 45678: 21}} and so on</p> <p>I...
<p>Making a small example using your data + an extra edge.</p> <pre><code>import pandas as pd import networkx as nx so = pd.DataFrame({ &quot;source&quot;: [1232, 1232 , 1232, 2345 ], &quot;target&quot;: [2342, 45678, 2345, 45678], &quot;weight&quot;: [12 , 21 , 1, 1] }) G = nx.from_pandas_edge...
python|pandas|graph|dijkstra
1
354,377
68,782,144
PyTorch: Can I group batches by length?
<p>I am working on an ASR project, where I use a model from HuggingFace (<code>wav2vec2</code>). My goal for now is to move the training process to PyTorch, so I am trying to recreate everything that HuggingFace’s <code>Trainer()</code> class offers.</p> <p>One of these utilities is the ability to group batches by leng...
<p>One possible way of going about this is by using a <em>batch sampler</em> and implementing a <code>collate_fn</code> for your dataloader that will perform the dynamic padding on your batch elements.</p> <p>Take this basic dataset:</p> <pre><code>class DS(Dataset): def __init__(self, files): super().__ini...
pytorch|pytorch-dataloader|huggingface-datasets
2
354,378
68,509,678
How to speed up iteration?
<p>I got this code, and I want to iterate over a csv file with ~100000 columns.</p> <p>This script do run very slowly to iterate over that number of columns.</p> <p>Do any of you have a possible solution to speed up my code?</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import math a=pd.read_...
<p><strong>Edit</strong></p> <p>The OP is having trouble reading the CSV file, presumably because of the 2-row header and the slightly unusual separator (and the decimal comma).</p> <p>Here is a way to read such a file:</p> <pre class="lang-py prettyprint-override"><code>a = pd.read_csv(io.StringIO(txt), sep=';', decim...
python|pandas
2
354,379
68,806,265
HuggingFace Trainer logging train data
<p>I'm following this tutorial to train some models:</p> <p><a href="https://huggingface.co/transformers/training.html" rel="nofollow noreferrer">https://huggingface.co/transformers/training.html</a></p> <p>I'd like to track not only the evaluation loss and accuracy but also the train loss and accuracy, to monitor over...
<p>You can use the methods <code>log_metrics</code> to format your logs and <code>save_metrics</code> to save them. Here is the code:</p> <pre><code># rest of the training args # ... training_args.logging_dir = 'logs' # or any dir you want to save logs # training train_result = trainer.train() # compute train result...
pytorch|huggingface-transformers
3
354,380
68,810,795
Filter rows in DataFrame where certain conditions are met?
<p>I have a DataFrame with relevant stock information that looks like this.</p> <p><a href="https://i.stack.imgur.com/A8aKr.png" rel="nofollow noreferrer">Screenshot of my dataframe</a></p> <p>I need it so that if the 'close' from one row is different from the 'open' in the next row a new dataframe will be created stor...
<p>This can be accomplished using <code>Series.shift</code></p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df['close'] != df['open'].shift(-1) 0 2020-01-01 False 1 2020-01-01 False 2 2020-01-01 True 3 2020-01-02 True 4 2020-01-02 True 5 2020-01-02 False 6 2020-01-03 Tru...
python|pandas
0
354,381
68,583,741
How to find out error percentage in pandas dataframe?
<p>I have sample work history data data where history of pieces of work moving through the system are recorded. To do so, I selected rows based on error status which is end with '1'. Now, I tried to find error percentage from it but the output doesn't make sense to me.</p> <p>Essentially, what I want to do is, I want ...
<p>Ok. if I get your explanation right all <code>status</code> ending with 1 are errors. So, here is a way to do this. Maybe not the most beautiful, but it does the trick.</p> <p>Step 1 is to create a column containing the last digit of the <code>status</code> number:</p> <pre><code>df['error'] = df['status'].astype(st...
python|pandas
2
354,382
68,729,349
getting mean() used in groupby to use the right grouped values for calculation
<p>Data import from csv:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Date</th> <th>Item_1</th> <th>Item 2</th> </tr> </thead> <tbody> <tr> <td>1990-01-01</td> <td>34</td> <td>78</td> </tr> <tr> <td>1990-01-02</td> <td>42</td> <td>19</td> </tr> <tr> <td>.</td> <td>.</td> <td>.</td> </tr...
<pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.read_csv( 'test.csv', index_col = 'date' ) df.index = pd.to_datetime( df.index ) df.groupby([(df.index.year),(df.index.month)]).mean() </code></pre> <p>Seems to do the trick from the provided data.</p>
python|pandas
1
354,383
68,616,366
Recognizing Date inside of a string type in a Pandas DataFrame
<p>I am attempting to recognize dates contained inside strings inside of a pandas dataframe. Inside of the csv file, the dates appear as: <code>'7\23\2019'</code>. However, when I printed the actual information to see what was contained inside of the cell, the following appeared: <code>7, 23, 2019</code>.</p> <p>My ori...
<p>use <code>concat()</code>+<code>to_datetime()</code>+<code>dropna()</code>+list comprehension:</p> <pre><code>output=pd.concat([pd.to_datetime(df[x],errors='coerce',format='%m/%d/%Y') for x in df.select_dtypes('O')],axis=1).dropna(axis=1,how='all') </code></pre> <p><strong>OR</strong></p> <p>use <code>select_dtypes(...
python|python-3.x|pandas|dataframe
0
354,384
68,566,562
How to go through the array halfway and then continue from the end of the array to the half array?
<p>I'm trying to loop through the array, so that we take the first two values from the array at once, then the following iterations will take one value at a time until half of the array. When it comes to the middle of the field, it starts the same way, but from the end of the field towards the beginning. It takes first...
<p>You can see the problem like that</p> <ul> <li><p>each group of values is printed the same way</p> </li> <li><p>you apply to the first half and to the second half in reverse</p> </li> </ul> <pre><code>def print_half(half_values): print(*half_values[:2]) print(*half_values[2:], sep=&quot;\n&quot;) def prin...
python|numpy|for-loop
0
354,385
68,867,081
Convert an array of objects into an array of arrays with Python
<p>I have a large .csv database with a column name VELOCITY containing 3D velocity vectors.</p> <p>Each element of the VELOCITY column has the form: '(v1, v2, v3)'</p> <p>To read the data I used:</p> <pre><code>df = pd.read_csv('database.csv') df = pd.DataFrame(df) </code></pre> <p>Now, I tried to define a velocity_arr...
<p>Seen from your sample data that each entry in the <code>velocity_array</code> has 2 single quotes enclosing the entry e.g. <code>'(a1, a2, a3)'</code>. Therefore, suppose your entries are actually string entries.</p> <p>If this is true, you can transform each string in the column to a list by:</p> <pre><code>df['VE...
python|arrays|pandas|numpy
3
354,386
68,825,672
Random Sparse Matrix in Python
<p>I want to create a random sparse matrix in python, where the non - zero elements are between 1 and 7 and the diagonal elements are zero. Also no row or column should have all elements zero. The % of zero elements also would be chosen randomly. Also, if i,j is non-zero, then j,i should be 0.</p> <p>I have the followi...
<p>a possible algorithm would be to pick coordinates from a list at ramdom and if the xy and yx are both available and x != y then set a value in that coordinate. continue until you have enough percentage fill.</p> <p>afterwards check that all rows have at-least one non-zero.</p>
python|matrix|graph|pytorch
0
354,387
68,633,825
how to convert a set of matrices into a data frame in pandas?
<p>I have four-time point matrices, A0, A1, A2, and A3, which are m*n matrices. I would like to make a data frame in pandas that involves these matrices and whenever I call them I can access them easily. Is that possible?</p> <p>For example <code>A0=np.array([1,2,3],[3,4,5])</code>, <code>A1=np.array([0,2,0],[3,4,0])...
<p>Well numpy and pandas are compatible in many builtin functions.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np numpy_data = np.array([[1, 2], [3, 4]]) df = pd.DataFrame(data=numpy_data) # If you know your column names column_names = ['first_col', 'second_col'] df = pd.DataFrame(data=numpy_da...
python|pandas|dataframe|matrix
0
354,388
68,544,019
Compare values between 2 dataframes and transform data
<p>The main aim of this script is to compare the regex format of the data present in the csv with the official ZIP Code regex format for that country, and if the format does not match, the script would carry out transformations on said data and output it all in one final dataframe.</p> <p>I have 2 csv files, one (count...
<p>Based on your response to my comment, I would suggest to directly fix the zip code using your regexes:</p> <pre><code>df3 = df2.set_index('Country') df1['corrected_Zip'] = (df1.groupby('Country') ['Zip Code'] .apply(lambda x: x.str.extract('(%s)' % df3.loc[x.nam...
python|regex|pandas|csv|formatting
1
354,389
36,669,219
Fastest way to find maximum value of a list in specific intervals
<p>I have a list that contains 1024 elements. I want to check the maximum value of the list between an interval that i determined.</p> <p>for example X is my list that is in numpy array form. Then;</p> <pre><code>if np.amax(X[0:31]) &gt; 200: print("1") elif np.amax(X[0:31]) &lt; 200: print("1a") if np.amax(...
<p>Well, for such regular intervals, a standard for-loop should do. For starters, this will work:</p> <pre><code>for x in xrange(0, 1024, 32): # 0, 32, 64, ... , 992 m = np.amax(X[x:x+32]) if m &gt; 200: print(str(x/32 + 1)) # 1, 2, 3, ... , 32 (not 16) elif m &lt; 200: print(str(x/32 + 1...
python|algorithm|performance|python-2.7|numpy
1
354,390
36,526,282
Append multiple pandas data frames at once
<p>I am trying to find some way of appending multiple pandas data frames at once rather than appending them one by one using </p> <pre><code>df.append(df) </code></pre> <p>Let us say there are 5 pandas data frames <code>t1</code>, <code>t2</code>, <code>t3</code>, <code>t4</code>, <code>t5</code>. How do I append the...
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="noreferrer"><code>concat</code></a>:</p> <pre><code>print pd.concat([t1, t2, t3, t4, t5]) </code></pre> <p>Maybe you can <code>ignore_index</code>:</p> <pre><code>print pd.concat([t1, t2, t3, t4, t5], ignor...
python|pandas|append
112
354,391
36,635,238
Specifying default dtype for np.array(1.)
<p>Is there a way to specify default dtype that's used with constructs like <code>np.array(1.)</code>?</p> <p>In particular I want <code>np.array(1.)</code> to be <code>np.float32</code> and <code>np.array(1)</code> to be <code>np.int32</code>. Instead I'm getting <code>np.float64</code> and <code>np.int64</code></p>
<p>The default depends on your system. On a 64-bit system, default types will be 64-bit. On a 32-bit system, default types will be 32-bit. There is no way to change the default short of re-compiling numpy with a different system C header.</p> <p>You can of course specify dtypes explicitly, e.g.</p> <pre><code>&gt;&gt...
python|numpy
9
354,392
36,588,171
pandas - perform string operation on all elements of a column
<p>I have a column in a pandas dataframe that is all capitals. I would like to change this to words with only the first letter capitalized.</p> <p>I have tried the following:</p> <pre><code>import pandas as pd data = pd.read_csv('my_file.csv') data['field'] = data['field'].title() </code></pre> <p>This returns the ...
<p>Found the answer here:</p> <p><a href="http://pandas.pydata.org/pandas-docs/stable/text.html" rel="noreferrer">http://pandas.pydata.org/pandas-docs/stable/text.html</a></p> <pre><code>data['field'] = data['field'].str.title() </code></pre>
python|string|pandas
10
354,393
36,462,100
Creating new column in pandas dataframe with a list of values from another column without using "groupby"
<p>I work with large datasets, making pandas group and groupby functions take a long time/use too much memory. I have heard some people say groupby can be slow, but am having trouble finding a better solution. </p> <p>If my dataframe has 2 columns similar to:</p> <pre><code>df = pd.DataFrame({'a':[1,2,2,4], 'b':[1,1,...
<p>On a 4K row df I get the following:</p> <pre><code>In [29]: df_group = df.groupby('a') ​ %timeit df.apply(lambda row: df_group.get_group(row['a'])['b'].tolist(), axis=1) %timeit df['a'].map(df.groupby('a')['b'].apply(list)) 1 loops, best of 3: 4.37 s per loop 100 loops, best of 3: 4.21 ms per loop </code></pre>
python|pandas
0
354,394
36,401,596
Convert data type object DD-Mon-YYYY to data format in Python
<p>I've loaded a csv using pd.read_csv in the following format - </p> <pre><code>obj = pd.read_csv('usd_brl_date.csv', sep=';', usecols=[1,2,3,4,5,6]) In [34]: obj Out [34]: Date Price Open High Low Change % 0 18/Mar/2016 3.6128 3.6241 3.6731 3.6051 -0.31% 1 17/Mar/2016 3.6241 ...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a>:</p> <pre><code>df['Date'] = pd.to_datetime(df['Date'], format="%d/%b/%Y") print df Date Price Open High Low Change % 0 2016-03-18 3.6128 ...
python|csv|pandas|strftime|strptime
0
354,395
36,676,150
Getting very high values in linear regression
<p>I am trying to make a simple MLP to predict values of a pixel of an image - <a href="http://evolvingstuff.blogspot.in/2012/12/generating-mona-lisa-pixel-by-pixel.html" rel="nofollow">original blog</a> . Here's my earlier attempt using Keras in python - <a href="https://github.com/goelakash/MonaNet/blob/master/MonaNe...
<p>First of all, I think that instead of running the train_op and then the MSE you can run both ops in a list and reduce your computational cost significantly. </p> <pre><code>for i in range(nb_epochs): cost += sess.run([MSE, train_op], feed_dict ={x: X_train, y: Y_train}) </code></pre> <p>Secondly, I suggest always ...
python|tensorflow|linear-regression
1
354,396
36,494,926
Combine two dataframe boxplots in a twinx figure
<p>I want to display two Pandas dataframes within one figure as boxplots. As each of the two dataframes has different value range, I would like to have them combined in a twinx figure.</p> <p>Reduced to the minimum, I have tried the following:</p> <pre><code>import pandas as pd import numpy as np import matplotlib.py...
<p>The best solution is to concatenate the data frames for plotting and to use a mask. In the creation of the mask, we use the <code>dfs == dfs | dfs.isnull()</code> to create a full matrix with <code>True</code> and then we query on all column names that are not <code>'E'</code> or <code>'F'</code>. This gives a 2D ma...
pandas|matplotlib|axis|boxplot
3
354,397
36,672,618
How to create a recurrent neural network in tensor flow for variable sequence length?
<p>I am trying the create a recurrent neural network in tensor flow. The input to the network is a sequence of vectors. The sequence length is different for all the inputs. I want to do this with batch of inputs.</p> <p>Can anyone help me on how exactly to do this? I have gone through the tutorials on the tensorflow s...
<p>You can use the rnn function defined <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/rnn.py#L35" rel="nofollow">here</a></p> <p>One of the arguments it takes is sequence_length</p> <blockquote> <p>sequence_length: Specifies the length of each sequence in inputs. An int...
tensorflow|recurrent-neural-network
2
354,398
36,569,827
Read txt data separated by empty lines as several numpy arrays
<p>I have some data in a txt file as follows:</p> <pre><code># Contour 0, label: 37 41.6 7.5 41.5 7.4 41.5 7.3 41.4 7.2 # Contour 1, label: 48.3 2.9 48.4 3.0 48.6 3.1 # Contour 2, label: 61.4 2.9 61.3 3.0 .... </code></pre> <p>So every block begins with a comment and ends with a bl...
<p>Like this?</p> <pre><code>import numpy as np text = \ ''' # Contour 0, label: 37 41.6 7.5 41.5 7.4 41.5 7.3 41.4 7.2 # Contour 1, label: 48.3 2.9 48.4 3.0 48.6 3.1 # Contour 2, label: 61.4 2.9 61.3 3.0 ''' for line in text.split('\n'): if line != '' and not line.startswith('...
python|arrays|numpy
3
354,399
36,255,918
SummaryWriter not writing summaries to file
<p>I'm trying to use tensorflow's SummaryWriter, however it does not seem to write events, images, or histograms to file. However it does write the graph to file, (which I can then see in tensorboard), indicating at least, tensorboard and SummaryWriter know where my logdir is. </p> <p>Here is my (simplified) code, bro...
<p>I know this is an old post, but I was experiencing the same thing in a virtual environment running TensorFlow 1.1.0. Running version 1.2.1 I don't seem to have this problem. You can execute the following at the command line to determine which version of TensorFlow you're running:</p> <pre><code>python -c "import ...
tensorflow|tensorboard
0