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
3,500
58,601,120
How to split record from a DataFrame cross pairs in pandas?
<p>I hava a dataframe like this :</p> <pre><code> a b c 0 A B 1 4 B A 1 1 C D -1 3 D C 3 2 E F 3 </code></pre> <p>The '0' row and '4'row are a pair, I will remove one row by the value of 'c' columns. According to 'c' columns, I decide to remove which one or remove all of them. If mirror pair have sa...
<p>first select the non-duplicated rows using <code>np.sort</code> and <a href="https://pandas.pydata.org/pandas-docs/version/0.25/reference/api/pandas.Series.duplicated.html" rel="nofollow noreferrer"><code>Series.duplicated</code></a> (see <strong>m1</strong> detail)</p> <p>Then you can use <a href="https://pandas.p...
python-3.x|pandas
1
3,501
58,208,274
Python: Array with too many Indices?
<p>I'm trying to understand the code below and what it does:</p> <pre><code>im = pilimage.open(img_path) image_array = np.array(im) imgstack = image_array[area[0]:area[1], area[2]:area[3], z_stack[0]:z_stack[1]] </code></pre> <p>I know that it opens up an image and stores it in <code>im</code> ...
<p>This is an advanced-ish application of the python slice notation which you can learn about here: <a href="https://stackoverflow.com/questions/509211/understanding-slice-notation">Understanding slice notation</a>. There are a couple nuances here though:</p> <ul> <li><code>area[0]:area[1]</code> is taking the <code>...
python|arrays|image|numpy|python-imaging-library
0
3,502
44,546,086
Remove one dataframe from another with Pandas
<p>I have two dataframes of different size (<code>df1</code> nad <code>df2</code>). I would like to remove from <code>df1</code> all the rows which are stored within <code>df2</code>.</p> <p>So if I have <code>df2</code> equals to:</p> <pre><code> A B 0 wer 6 1 tyu 7 </code></pre> <p>And <code>df1</code> eq...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="noreferrer"><code>merge</code></a> with outer join with filter by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html" rel="noreferrer"><code>query</code></a>, last remove helper column b...
python|pandas|dataframe|compare|difference
17
3,503
61,019,326
asfreq yields unexpected results with Period dtype
<p>When upsampling a Dataframe, I would to like that new rows created are left empty.</p> <p>Considering following code:</p> <pre><code>import pandas as pd p5h = pd.period_range(start='2020-02-01 00:00', end='2020-03-04 00:00', freq='5h', name='p5h') df = pd.DataFrame({'Values' : 1}, index=p5h) </code></pre> <p>I ...
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Period.asfreq.html#pandas.Period.asfreq" rel="nofollow noreferrer"><code>asfreq()</code></a> is indeed a method for <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Period.html" rel="nofollow noreferrer"><code>Period...
python|pandas|period
3
3,504
60,848,403
Pycharm interperter uses the wrong path
<p>I am trying to follow <a href="https://github.com/huggingface/transformers#quick-tour-of-the-fine-tuningusage-scripts" rel="nofollow noreferrer">this</a> instructions. I downloaded the Glue dataset, and I am trying to run this command</p> <pre><code>python ./examples/run_glue.py \ --model_type bert \ --mode...
<p>The problem was the versions of the transformers module, the interpreter was set correctly </p>
python|pycharm|huggingface-transformers
0
3,505
60,846,087
Renaming column name based on its value Pandas
<p>I have the following data frame. </p> <pre><code>df col_1 col_2 col_3 min1 max1 target1 min2 max2 target2 </code></pre> <p>I would like to rename columns col_1, col_2, col_3 based on their value as Min, Max, and Target respectively. I would like to have something below as a result. </p> <...
<p>Well, I am not sure that you <strong>should</strong> rename columns this way, but here is a way you <strong>could</strong> do it. First <a href="https://stackoverflow.com/questions/41719259/how-to-remove-numbers-from-string-terms-in-a-pandas-dataframe">remove numbers from string</a> and then use the <a href="https:/...
python|pandas|dataframe
2
3,506
71,692,261
Nested column names in pandas rows, trying to do an unstack type operation
<p>I have this code and dataframe</p> <pre><code>df_initial = pd.DataFrame(data = {'ref':['02','NaN','NaN','NaN','03','NaN','NaN','NaN'], 'Part_ID':['1234-1', 'Shop_Work','repair','scrap','4567-2','Shop_Work','clean','overhaul']}) </code></pre> <p><a href="https://i.stack.imgur.com/fsUVZ.png" rel="nofollow noreferrer">...
<p>Use:</p> <pre><code>#if NaNs are string replace to missing values df_initial['ref'] = df_initial['ref'].replace('NaN', np.nan) #test missing values m = df_initial['ref'].isna() #forward filling missing values df_initial['ref'] = df_initial['ref'].ffill() #new column Shop_Work df_initial['Shop_Work'] = df_initial['P...
python|pandas
1
3,507
69,947,446
Sorting Algorithm according to match/mismatch
<p>The data I'm working on represent the presence or the absence of some species in 5 habitats. I want to obtain clusters according to the shared zones between them, basically i want to maximize the matches between elements for each species.<br /> This is the original dataset <img src="https://i.stack.imgur.com/H6XIa.p...
<p>I think I solved this problem in a simple yet appropriate way (I'm sure there may be better algorithms though). I check the number of matches between each couple of boolean vectors:</p> <pre class="lang-py prettyprint-override"><code>n=len(diet_bool_df['Prey']) match_mtx = [[0 for i in range(n)] for j in range(n)] #...
python|pandas|dataframe|sorting|cluster-analysis
0
3,508
43,068,785
Speed up nested for-loops in python / going through numpy array
<p>Say I have 4 numpy arrays A,B,C,D , each the size of (256,256,1792). I want to go through each element of those arrays and do something to it, <em>but</em> I need to do it in chunks of 256x256x256-cubes.</p> <p>My code looks like this:</p> <pre><code>for l in range(7): x, y, z, t = 0,0,0,0 for m in range(...
<p>Since you update <code>t</code> with every element of <code>m in range(a.shape[0])</code>, <code>n in range(a.shape[1])</code> and <code>o in range(256*l,256*(l+1))</code>, you can substitute:</p> <pre><code>for m in range(a.shape[0]): for n in range(a.shape[1]): for o in range(256*l,256*(l+1)): ...
python|arrays|numpy|for-loop
1
3,509
72,344,379
How can I make dictionary key as column of dataframe?
<pre><code>!pip install -U LeXmo from LeXmo import LeXmo df['Dict'] = df['Content '].apply(lambda x: [LeXmo.LeXmo(x)]) </code></pre> <p>Using this snippet , I am able to generate this</p> <p><a href="https://i.stack.imgur.com/e9Dv2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e9Dv2.png" alt="enter...
<p>You can convert output from <code>LeXmo.LeXmo(x)</code> to <code>Series</code>, so it create new columns if call function in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.apply.html" rel="nofollow noreferrer"><code>Series.apply</code></a>, last append to original DataFrame by <a hr...
python|pandas|dataframe|dictionary|nlp
1
3,510
72,259,405
pandas evaluating strings as numeric
<p>assume df as;</p> <pre><code>data = {'duration':['1week 3day 2hour 4min 23', '2hour 4min 23sec', '2hour 4min', np.nan, '', '23sec']} df = pd.DataFrame(data) </code></pre> <p>I'm trying to calculate the duration as sum of seconds. Replaced the values as:</p> <pre><code>df['duration'] = df['duration'].str.replace('wee...
<p>You can use a regex combined to a custom function to replace weeks by 7 days and add seconds on lonely numbers (you can add other units). Then convert <a href="https://pandas.pydata.org/docs/reference/api/pandas.to_timedelta.html" rel="nofollow noreferrer"><code>to_timedelta</code></a>:</p> <pre><code>def change_uni...
python|pandas|eval
2
3,511
50,462,988
Split lists within dataframe column into multiple columns
<p>I have a Pandas DataFrame column with multiple lists within a list. Something like this:</p> <pre><code>df col1 0 [[1,2], [2,3]] 1 [[a,b], [4,5], [x,y]] 2 [[6,7]] </code></pre> <p>I want to split the list over multiple columns so the output should be something like:</p> <pre><code> col1 col2 ...
<p>You can use <code>pd.Series.apply</code>:</p> <pre><code>df = pd.DataFrame({'col1': [[[1, 2], [2, 3]], [['a', 'b'], [4, 5], ['x', 'y']], [[6, 7]]]}) res = df['col1'].apply(pd.Series) print(res) 0 1 2 0 [1, 2] [2, 3] NaN 1 [a, b] ...
python|pandas
7
3,512
45,694,517
Add, Delete, Edit Rows and Columns while Iterating PANDAS DATAFRAME
<p>I have a csv file with over 50,000 tweets that I open as DataFrame with Pandas</p> <pre><code>df = pd.read_csv('dataset_tweets.csv') </code></pre> <p><a href="https://i.stack.imgur.com/5Diyo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5Diyo.png" alt="enter image description here"></a></p> <...
<p>say you have some 'text normalising' function:</p> <pre><code>def normalises_text(text): .... return normalised_text </code></pre> <p>You can apply this 'row-wise' to your 'text' column and put this in a new column very simply , as follows:</p> <pre><code>df['normalised_text'] = df.text.apply(normalises_t...
python|pandas|dataframe
2
3,513
45,525,270
Multidimensional array in numpy
<p>I have an array of shape <code>(5,2)</code> which each row consist of an array of shape <code>(4,3,2)</code> and a float number.</p> <p>After I slice that array<code>[:,0]</code>, I get an array of shape <code>(5,)</code> which each element has shape of <code>(4,3,2)</code>, instead of an array of shape <code>(5,4,...
<p>You have an array of <em>objects</em>; You can use <code>np.stack</code> to convert it to the shape you need if you are sure all the sub elements have the same shape:</p> <pre><code>np.stack(a[:,0]) </code></pre> <hr> <pre><code>a = np.array([[np.arange(24).reshape(4,3,2), 1.]]*5) a.shape # (5, 2) a[:,0].shape ...
python|numpy|multidimensional-array
2
3,514
62,585,169
Data frame with duplicates in a column map to another column
<pre><code>import pandas as pd df = pd.DataFrame({ &quot;col1&quot;: [11, 12, 13], &quot;col2&quot;: [21, 22, 23], &quot;col3&quot;: [31, 32, 33], &quot;col4&quot;: [41, 42, 43], }) </code></pre> <p>I have a Pandas data frame like <code>df</code> above, and I would like to reshape <code>df</code> t...
<p>You need <code>melt</code>, <code>merge</code> and <code>replace</code></p> <pre><code>d = {'col2': 'do', 'col3': 're', 'col4': 'me'} df_final = (df.melt(['col1','col5','col6'], var_name=&quot;indx&quot;, value_name=&quot;colA&quot;) .merge(df[['col1','col4']], how='left').replace(d)) Out[522]: ...
python|pandas|dataframe
2
3,515
54,689,438
Pods unschedulable error while deploying tensorflow serving model to kubernetes using GPUs
<p>I am getting two errors after deploying my object detection model for prediction using GPUs:</p> <p>1.PodUnschedulable Cannot schedule pods: Insufficient nvidia</p> <p>2.PodUnschedulable Cannot schedule pods: com/gpu.</p> <p>I have two node pools. One of them is configured to have Tesla K80 GPU and auto scaling e...
<p>Issue seems to be with the resources not being available to run the pod. the pod contains two containers that needs min 1.5Gi Memory and 1.5 cpu and max 5GB memenory and 5 cpu.</p> <p>controller is not able to identify the node that meets the resource requirements for running the pod and hence it is not getting sch...
tensorflow|kubernetes|google-cloud-platform|nvidia|google-kubernetes-engine
1
3,516
73,722,058
Pandas groupby multiple columns with value_counts function
<p>I want to apply <code>value_counts()</code> to multiple columns and reuse the same dataframe further to add more columns. I have the following dataframe as an example.</p> <pre><code> id shop type status 0 1 mac A open 1 1 mac B close 2 1 ikea B open 3 1 ikea ...
<p>You can do with <code>groupby()</code> and <code>value_counts</code>:</p> <pre><code>groups = df.groupby(['id','shop']) pd.concat([groups['type'].value_counts().unstack(fill_value=0), groups['status'].value_counts().unstack(fill_value=0)], axis=1).reset_index() </code></pre> <p>Or a bit more dy...
python|pandas|dataframe
3
3,517
71,130,161
Performing Differentiation wrt input within a keras model for use in loss
<p>Is there any layer in keras which calculates the derivative wrt input? For example if <code>x</code> is input, the first layer is say <code>f(x)</code>, then the next layer's output should be <code>f'(x)</code>. There are multiple question here about this topic but all of them involve computation of derivative outsi...
<p>Not sure what exactly you want to do, but maybe try a custom <code>Keras</code> layer with <code>tf.gradients</code>:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf tf.random.set_seed(111) class GradientLayer(tf.keras.layers.Layer): def __init__(self): super(GradientLayer, self)._...
python|tensorflow|keras|tensorflow2.0
3
3,518
71,413,160
TypeError: forward() got an unexpected keyword argument 'return_dict' BERT CLASSIFICATION HUGGINFACE with tuning
<p>I'm stacked with this model, every day errors came to my code! Anyway I'm trying to implement a Bert Classifier to discriminate between 2 sequences classes (BINARY CLASSIFICATION), with AX hyperparameters tuning. This is all my code implemented anticipated by a sample of my datasets ( I have 3 csv, train-test-val). ...
<p>In <code>net_train</code> you call:</p> <pre class="lang-py prettyprint-override"><code>outputs,x= net(input_ids, attention_mask,return_dict=True) </code></pre> <p>but your object <code>net</code> only accepts two parameters despite <code>self</code> as defined in <code>BERT_Arch</code>:</p> <pre class="lang-py pret...
python|pytorch|huggingface-transformers|bert-language-model|ray
0
3,519
71,198,417
TensorBoard GPU profiling with Tensorflow Agents
<p>I would like to profile my GPU usage when training agents from <a href="https://github.com/tensorflow/agents" rel="nofollow noreferrer">tensorflow/agents</a>, but I cannot figure out how. Specifically I am trying to profile my GPU when running this <a href="https://github.com/tensorflow/agents/blob/master/tf_agents/...
<p>You can use the <code>tf.profiler</code> module, which is what the TensorBoard callback does <a href="https://github.com/keras-team/keras/blob/v2.8.0/keras/callbacks.py#L2608-L2637" rel="nofollow noreferrer">under the hood</a>.</p> <p>The agent example you linked uses a custom training loop, one possibility would be...
tensorflow|gpu|tensorboard
1
3,520
52,447,633
Python Script, Pandas Special Characters
<p>I am using this script to geocode addresses. The script works fine, however the output file converts special characters such as <code>中央区</code> and <code>Athénée</code> to gibberish. i.e.</p> <p><code>中央区</code> -> <code>中央区</code></p> <p><code>Athénée</code> -> <code>Athénée</code></p> <p>The input file...
<p>If I insert the line:</p> <pre><code>data['Address'] = data['Address'].map(lambda x: x.encode('unicode-escape').decode('utf-8')) </code></pre> <p>to decode and re-encode the inputs - then output becomes.</p> <p><code>中央区</code> -> <code>\u4e2d\u592e\u533a</code> instead of <code>中央区</code></p> <p>which is ...
python|pandas
0
3,521
60,599,607
ImportError: cannot import name 'UnicodeWriter' from 'pandas.io.common'
<p>I am getting this error in this line:</p> <pre><code>sample_submission.to_csv('submissions/submission.csv', index=False, float_format='%.4f') </code></pre> <p><strong>Traceback:</strong></p> <pre><code>--------------------------------------------------------------------------- ImportError ...
<p>What is your pandas version? This does not happen in pandas 1.0.1. May be try upgrading your pandas to see if you still get the error.</p>
python|python-3.x|pandas
2
3,522
72,750,343
How convert this Pytorch loss function to Tensorflow?
<p>This Code for a paper I read had a loss function written using Pytorch, I tried to convert it as best as I could but am getting all Zero's as model predictions, so would like to ask the following:</p> <ol> <li>Are the methods I used the correct equivalent in Tensorflow?</li> <li>Why is the model predicting only Zero...
<p>Try this <code>custom_loss</code>:</p> <pre><code>def custom_loss(y_pred, y_true): alpha = 2.0 loss = (y_pred - y_true) ** 2.0 adj = tf.math.multiply(y_pred,y_true) adj = tf.where(tf.greater(adj, 0.0), tf.constant(1/alpha), adj) adj = tf.where(tf.less(adj, 0.0), tf.constant(alpha), adj) loss ...
python|tensorflow|deep-learning|pytorch|tensor
1
3,523
59,850,305
Pandas Plot with Bar Returns Sorted by Counts?
<p>I am using the following code to create a plot of how many nulls appear in my df, sorted by the date column:</p> <pre><code>df[df['Gas'].isnull()]['ReportDate_Time'].sort_values().value_counts().plot() </code></pre> <p><a href="https://i.stack.imgur.com/RSPrq.png" rel="nofollow noreferrer"><img src="https://i.stac...
<p>If I understand correctly, you just need to sort your dataframe by report date, <code>sort_values('Reportdate')</code></p> <p>see below for an example. </p> <pre><code>dates = pd.date_range(pd.to_datetime('2020-01-21'), pd.to_datetime('2020-02-01'),freq='D') vals = np.random.randint(0,500,size=len(dates)) df = pd....
python|pandas|plot|bar-chart
1
3,524
59,857,571
Why randn doesn't always have a mean of 0 and variance of 1?
<p>For the <a href="https://pytorch.org/docs/stable/torch.html?highlight=randn#torch.randn" rel="nofollow noreferrer">PyTorch.randn()</a> method the documentation says:</p> <blockquote> <p>Returns a tensor filled with random numbers from a normal distribution with mean <code>0</code> and variance <code>1</code> (a...
<p>It would be a big coincidence that a finite sample of the distribution has <strong>exactly</strong> the same mean and <strong>exactly</strong> the same standard deviation. It is to be expected that the more numbers you generate, the closer the mean and deviation of the sample approaches the "true" mean and deviation...
python|random|pytorch|tensor
5
3,525
59,786,177
Find difference between two pandas dataframes when both contains same rows but one dataframe contains it more than once
<p>I have two pandas dataframes</p> <p>df1</p> <pre><code>jon,12,NewYork jon,12,NewYork james,14,LA </code></pre> <p>df2</p> <pre><code>jon,12,NewYork james,14,LA </code></pre> <p>I want to compare them and get the difference as below</p> <p>deltaDF</p> <pre><code>jon,12,NewYork </code></pre> <p>I tried <code>p...
<p>You can add a new column to catch the duplicates:</p> <pre><code>df1['merge'] = df1.groupby(['0','1','2']).cumcount() df2['merge'] = df2.groupby(['0','1','2']).cumcount() pd.concat([df1,df2]).drop_duplicates(keep=False) </code></pre> <p>Afterwards you can drop the added column again</p>
python|pandas|dataframe
2
3,526
32,533,722
last value carried forward in pandas
<p>I have 20 minutes of observed data, in 5 minute bins as follows:</p> <pre><code> bin var1 var2 var3 var4 5 -76.30 71.96 557.79 0.06 10 -61.23 78.14 600.69 0.09 15 -54.36 73.63 630.71 0.03 20 -12.41 71.46 661.19 0.08 </code></pre> <p>I need to model for an hour of da...
<p>While you can append to the DataFrame, it's a relatively inefficient operation, as each step takes a copy. <a href="http://pandas.pydata.org/pandas-docs/stable/basics.html#reindexing-and-altering-labels" rel="nofollow"><code>reindex</code></a> provides an easy way to align the data to a new index, then you can forw...
python|pandas
4
3,527
40,367,510
Deep learning Gradient at last but output layer is always zero
<p>I have been working with udacity self driving challenge#2. What ever changes I make to the deep network like learning rate, activation function, i am getting gradient zero issue while training. I have used both cross entropy loss and mse loss. For cross entropy 100 classes are used with degree difference of 10 i.e r...
<p>This seems to be vanishing gradient problem, 1.) Have you tried Relu? (I know you said you have tried diff activation fn) 2.) Have you tried reducing # of layers? 3.) Are your features normalized?</p> <p>There are architectures designed to prevent this as well (ex. <a href="https://www.quora.com/How-does-LSTM-hel...
tensorflow|deep-learning
0
3,528
40,660,716
numpy append slices to two dimensional array to make it three dimensional
<p>I have <code>5</code> numpy arrays with <code>shape (5,5)</code>. What I want to achieve is to combine these <code>5</code> numpy arrays to one array of shape (5,5,5). My code looks like the following but does not work:</p> <pre><code>combined = np.empty((0, 5, 5), dtype=np.uint8) for idx in range(0, 5): array...
<p>I have figured it out by myself:</p> <pre><code>combined = np.empty((0, 5, 5), dtype=np.uint8) for idx in range(0, 5): array = getarray(idx) # returns an array of shape (5,5) array array[np.newaxis, :, :] combined = np.append(combined, img, axis=0) print combined.shape + returns (5,5,5) </code></pre>
python|arrays|numpy|multidimensional-array|append
1
3,529
61,640,412
How can I get multiple dataframes returned from a class function?
<p>So I have made a class that takes in a ticker symbol, and it returns a dataframe with all the price information for the dates specified. here is the code below:</p> <pre><code>import pandas as pd import numpy as np import pandas_datareader as pdr # class to get stock price class GetStockInfo(): ''' Class...
<p>You could put the dataframes in a list and return that. Or better yet, in a dictionary:</p> <pre class="lang-py prettyprint-override"><code>results = {} for i in symbols: stock = GetStockInfo(i) results[i] = stock.build_df('2019-01-01', '2020-01-01') return results </code></pre>
python|pandas|dataframe|oop
1
3,530
61,676,600
How to use map and lambda function to convert a column in pandas to datetime?
<p>I have a column that has time like 9:3:15 (no leading 0s) (3 mins and 15 sec past 9). I would like to plot this (no date, just time) on the x axis. so i tried the following code: </p> <pre><code>def data_vis(dayN): plt.subplots_adjust(bottom=0.2) plt.xticks( rotation=25 ) ax=plt.gca() #ax.xaxis_date...
<p>not sure what's going wrong here; the following works fine for me:</p> <pre><code>import pandas as pd import numpy as np from matplotlib import pyplot as plt import matplotlib.dates as md # create a dummy df... dayN = pd.DataFrame({"Temperature(deg C)": np.random.rand(10)+20, "Time Stamp": ['9:...
pandas|datetime|matplotlib|time
0
3,531
61,935,573
Turn NaN in dataframe if condition met
<p>I have a column here that looks like this and is part of a dataframe:</p> <pre><code>df.Days_Since_Earnings Out[5]: 0 21.0 2 1.0 4 1000.0 5 500.0 6 119.0 Name: Days_Since_Earnings, Length: 76, dtype: float64 </code></pre> <p>I want to leave it as it is except I want to turn numbers above 120...
<p>You can use <code>mask</code>:</p> <pre><code>df['Days_Since_Earnings'] = df.Days_Since_Earnings.mask(df.Days_Since_Earnings &gt; 120) </code></pre> <p>or <code>where</code> with reverse condition</p> <pre><code>df['Days_Since_Earnings'] = df.Days_Since_Earnings.where(df.Days_Since_Earnings &lt;= 120) </code></pr...
python|pandas|dataframe|filter|filtering
2
3,532
62,017,979
Python Generate unique ranges of a specific length and categorize them
<p>I have a dataframe column which specifies how many times a user has performed an activity. eg. </p> <pre><code>&gt;&gt;&gt; df['ActivityCount'] Users ActivityCount User0 220 User1 190 User2 105 User3 109 User4 271 User5 265 ... User95 64 User96 15 User97 168 User98 25...
<p>The natural way to do that would be to split the data into 5 quanties, and then split the data into bins based on these quantities. Luckily, pandas allows you do easily do that: </p> <pre><code>df["category"] = pd.cut(df.Activity, 5, labels= ["a","b", "c", "d", "e"]) </code></pre> <p>The output is something like: ...
python|pandas|numpy
2
3,533
58,089,770
Using apply function Dataframe
<p>I need help correcting an error I am getting.</p> <p>I have the following dataframe:</p> <pre><code>x = [-0.75853, -0.75853, -0.75853, -0.75852] y = [-0.63435, -0.63434, -0.63435, -0.63436] z = [-0.10488, -0.10490, -0.10492, -0.10495] w = [-0.10597, -0.10597, -0.10597, -0.10596] df = pd.DataFrame([x, y, z, w], co...
<p>You should using <code>apply</code> like </p> <pre><code>df.apply(lambda x : roll(x['w'],x['x'],x['y'],x['z']),1) Out[291]: 0 -2.175472 1 -1.909103 2 -0.394163 3 -0.397885 dtype: float64 </code></pre>
python-3.x|pandas|math|apply
4
3,534
58,145,617
ValueError: could not convert string to float: ' 2,019,278 ' - potentially illegal character or format?
<p>I am having an issue with a format conversion from object to 'float64'. I cannot perform any matrix operations until this conversion occurs and in general this is a major annoyance because I am getting caught up in the weeds...</p> <p>Potentially it has to do with the inclusion of a space or a space and an apostrop...
<p>Do first this:</p> <pre><code>df_temp = df_By_Race_Disability.applymap(lambda x: x.replace(',', '')) </code></pre> <p>Then you can continue with your code</p> <pre><code>a = pd.DataFrame.to_numpy(df_temp, dtype=None, copy=False) a = a.astype('float64') </code></pre>
numpy
0
3,535
57,897,080
Load custom loss with extra input in keras
<p>I have a custom loss function that takes the input to the model as one of the arguments. If I load in the same session in which I train, I can load it no problem using <a href="https://stackoverflow.com/questions/48373845/loading-model-with-custom-loss-keras">this</a> technique.</p> <pre class="lang-py prettyprint-...
<p>An alternate way is to compute the loss inside a Keras layer and pass a dummy loss function that just returns the model's output as the loss in the compile method. There are other ways of doing this. But this is the one that I prefer.</p> <pre><code>import tensorflow as tf print('Tensorflow', tf.__version__) def c...
python|tensorflow|keras
3
3,536
57,875,425
Python - Pandas replacing dataframe column values - column data stored as list (i.e., '[this, that,'])
<p>I've tried a bunch of different things and I'm assuming I'm close here. I have a list of words that I generated from research abstracts courtesy of the Gensim keyword summarizer. The data is accurate, however it's stored as a list for each row and I want to get rid of the [' and '] for each row. I tried the code ...
<p>Is this what you're looking for</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import re rgx = lambda x: re.sub("']","",x) rgx = np.vectorize(rgx) df['newnlpkeywords'].values = rgx(df['newnlpkeywords'].values) </code></pre> <p>The following code applies the rgx function to every row in d...
python|pandas|list|text|replace
1
3,537
34,080,909
Pandas : Add new column with function based on index
<p>Let say I have a series <code>s</code></p> <pre><code>index_column size A 1 B 2 C 3 D 4 </code></pre> <p>I want to add a new column contains a function <code>f</code></p> <pre><code>def f(index_column): % do something return string </code></pre> ...
<p>Here is one way to do it with a DataFrame:</p> <pre><code>import pandas as pd def app_Z(s): """Append 'Z' onto column data""" return s+'Z' # recreate the series s = pd.Series(data=[1,2,3,4], index=['A','B','C','D'], name='Size') # create DataFrame and apply function to column 'Index' df = pd.DataFrame(s)...
python|pandas
8
3,538
33,997,753
Calculating pairwise correlation among all columns
<p>I am working with large biological dataset.</p> <p>I want to calculate PCC(Pearson's correlation coefficient) of all 2-column combinations in my data table and save the result as DataFrame or CSV file.</p> <p>Data table is like below:columns are the name of genes, and rows are the code of dataset. The float number...
<pre><code>from pandas import * import numpy as np from libraries.settings import * from scipy.stats.stats import pearsonr import itertools </code></pre> <p>Creating random sample data:</p> <pre><code>df = DataFrame(np.random.random((5, 5)), columns=['gene_' + chr(i + ord('a')) for i in range(5)]) print(df) ge...
python|pandas|correlation
19
3,539
37,097,207
How to Print a specific column in a 3D Matrix using numpy Python
<p>I have a problem with printing a column in a numpy 3D Matrix. Here is a simplified version of the problem:</p> <pre><code>import numpy as np Matrix = np.zeros(((10,9,3))) # Creates a 10 x 9 x 3 3D matrix Matrix[2][2][6] = 578 # I want to print Matrix[2][x][6] for x in range(9) # the purpose of this is that I want t...
<p>Slicing would work:</p> <pre><code>a = np.zeros((10, 9, 3)) a[6, 2, 2] = 578 for x in a[6, :, 2]: print(x) </code></pre> <p>Output:</p> <pre><code>0.0 0.0 578.0 0.0 0.0 0.0 0.0 0.0 0.0 </code></pre>
python|numpy|matrix|multidimensional-array
3
3,540
54,757,652
Drop all rows that *do not* contain any NaNs in their columns
<p>I use to drop the rows which has one cell with NAN value with this command:</p> <pre><code>pos_data = df.iloc[:,[5,6,2]].dropna() </code></pre> <p>No I want to know how can I keep the rows with NAN and remove all other rows which do not have NAN in one of their columns. my data is Pandas dataframe.</p> <p>Thanks....
<p>Use boolean indexing, find all columns that have at least <em>one</em> NaN in their rows and use the mask to filter.</p> <pre><code>df[df.iloc[:, [5, 6, 2]].isna().any(1)] </code></pre> <p>The DeMorgan equivalent of this is:</p> <pre><code>df[~df.iloc[:, [5, 6, 2]].notna().all(1)] </code></pre> <hr> <pre><code>...
python|python-3.x|pandas|dataframe
2
3,541
54,748,478
pandas df - calculate percentage difference not change
<p>I want to calculate the percentage difference not change or just the difference between two values. </p> <p>my df:</p> <pre><code> Radisson Collection 6 Total awareness 0.440553 Very/Somewhat ...
<p>Divide difference by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.diff.html" rel="nofollow noreferrer"><code>diff</code></a> with absolute values by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.abs.html" rel="nofollow noreferrer"><code>abs</code></a> wi...
python|pandas
2
3,542
49,465,836
Replacing Unicode character in pandas Dataframe column
<p>I have a problem with a pandas Dataframe that amongst other things contains the number of rooms in an apartment (type String). </p> <p>This data consists of a unicode character <strong>u"\u00BD"</strong> (<a href="https://www.fileformat.info/info/unicode/char/00bd/index.htm" rel="nofollow noreferrer">https://www.fi...
<p>You can fix your column with:</p> <pre><code>df['rooms'] = df['rooms'].str.replace("½", ".5") </code></pre> <p>To make it a float:</p> <pre><code>df['rooms'] = df['rooms'].str.replace("½", ".5").apply(float) </code></pre>
python|pandas|replace
1
3,543
73,224,541
Tensorflow Recommender - Saving large model with ScaNN index - memory bottleneck
<p>I have a relatively large TF retrieval model using the TFRS library. It uses a <a href="https://github.com/google-research/google-research/tree/master/scann" rel="nofollow noreferrer">ScaNN</a> layer for <a href="https://www.tensorflow.org/recommenders/api_docs/python/tfrs/layers/factorized_top_k/ScaNN" rel="nofollo...
<p>I think you are saving the TF model after training was completed. You just need the saved model to get trained weights from the model.</p> <p>You can try the following code:</p> <pre><code> sku_ids = df['SKU_ID'] sku_ids_list = sku_ids.to_list() q = embedding(sku_ids, output_mode='distance_matrix') di...
python|tensorflow
0
3,544
73,286,833
Year over Year difference and selecting maximum row in pandas
<p>I have a dataframe given as below:</p> <pre><code>ID YEAR NPS 500 2020 0 500 2021 0 500 2022 0 501 2020 32 501 2021 52 501 2022 99 503 2021 1 503 2022 4 504 2020 45 504 2021 55 504 2022 50 </code></pre> <p>I have to calculate y...
<p>If years are consecutive per <code>ID</code> first use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.diff.html" rel="nofollow noreferrer"><code>DataFrameGroupBy.diff</code></a>:</p> <pre><code>df = df.sort_values(['ID','YEAR']) df['nps_gain_yoy'] = df.groupb...
python|pandas|dataframe
0
3,545
73,418,067
How to search for name in dataframe
<p>For example I want to find all the people that has &quot;Abbott&quot; in their name</p> <pre><code>0 Abbing, Mr. Anthony 1 Abbott, Mr. Rossmore Edward 2 Abbott, Mrs. Stanton (Rosa Hunt) 3 Abelson, Mr. Samuel 4 Abelson, Mrs. Samuel (Hannah Wi...
<p>You can use <code>str.contains</code> with the column you are interested in searching</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df = pd.DataFrame(data={'Name': ['Smith', 'Jones', 'Smithson']}) &gt;&gt;&gt; df Name 0 Smith 1 Jones 2 Smithson &gt;&gt;&gt; df[df['Name'].str.contains('...
python|pandas
1
3,546
73,363,295
How can I split sub-strings to new rows of a dataframe?
<p>I have a dataframe which contains data that is entered without whitespace between words, i.e VolvoSaabVauxhall = Volvo Saab Vauxhall. I want to separate each word and insert new rows for each word that contain same data as row they originated from -</p> <pre><code>type year colour Mazda ...
<p>you say</p> <blockquote> <p>it's always a Capital letter preceded by a lower case letter</p> </blockquote> <p>so a regex for it is</p> <pre><code>[A-Z][^A-Z]* </code></pre> <p>capital letter ([A-Z]), followed by zero or more (*) not-capital letters (with ^).</p> <ul> <li>So we can <code>findall</code> such matches</...
python|pandas|data-wrangling
2
3,547
73,441,628
Map pandas column to numpy array
<p>I have a pandas dataframe which has a column containing index to be mapped.</p> <p>df:</p> <pre><code>Date Value id 01-01-2011 99 -9999 01-02-2011 0 -9999 01-03-2011 5 4 01-01-2012 0 9 01-02-2012 1 0 01-03-2012 5 15 01-01-2013 11 -9999 01-02-2013 9 13 01-03-2013 1 22 </code></pre> <p>Th...
<p>Looks like a merge to me.</p> <pre class="lang-py prettyprint-override"><code>numpy_array = np.random.rand(df.id.max() + 1) df2 = df.merge(pd.Series(numpy_array, name='value_from_array'), left_on=&quot;id&quot;, right_index=True, how=&quot;left&quot;) &gt;&gt;&gt; df2 ...
python|pandas
0
3,548
73,333,230
regex = False doesn't exist in str.split
<p>I am trying to split strings in my column using str.split: <code>str.split(&quot;. &quot;, regex = False)</code>. But when I do that, I get error:</p> <p><code>split() got an unexpected keyword argument 'regex'</code></p> <p>why it happens? regex should exist in that method: <a href="https://pandas.pydata.org/docs/...
<p><code>str.split</code> is a function in the <code>str</code> (string) class.</p> <p>You want to use: <code>my_series.str.split(&quot;. &quot;, regex = False)</code></p>
python|python-3.x|pandas|string|split
1
3,549
73,195,820
Create 2d image from point cloud
<p>I am trying to project a point cloud into a 2d image as if it were a satellite image.</p> <p>I have six files I want to project and the point clouds are quite big. For the biggest one, I have <code>len(las.X) = 37_763_608</code>, <code>max(las.X) - min(las.X) = 122_124</code>, and <code>max(las.X) - min(las.X) = 273...
<p>To interpolate, there are lots of libraries.</p> <p>This uses cubic interpolation, but it only works inside the convex hull, so the points outside the convex hull are taken from the nearest neighbor.</p> <p>If you are interpolating GIS data, you may look on Krigging interpolation, which should interpolate outside th...
python|numpy|point-clouds
1
3,550
35,034,389
Applying a Fast Coordinate Transformation in Python
<p>I have a simple 2x2 transformation matrix, <strong>s</strong>, which encodes some liner transformation of coordinates such that <strong>X' = sX</strong>.</p> <p>I have generated a set of uniformley distributed coordinates on a grid using the <strong>np.meshgrid()</strong> function and at the moment I traverse each ...
<p>You can use the numpy <code>dot</code> function to get the dot product of your matices as:</p> <pre><code>xx_tn,yy_tn = np.dot(s,[xx.flatten(),yy.flatten()]) xx_t = xx_tn.reshape((image_dimension, image_dimension)) yy_t = yy_tn.reshape((image_dimension, image_dimension)) </code></pre> <p>Which is much faster</p>
python|numpy|grid|transform|coordinate
4
3,551
31,144,356
Numpy indexing 3-dimensional array into 2-dimensional array
<p>I have a three-dimensional array of the following structure:</p> <pre><code>x = np.array([[[1,2], [3,4]], [[5,6], [7,8]]], dtype=np.double) </code></pre> <p>Additionally, I have an index array</p> <pre><code>idx = np.array([[0,1],[1,3]], dtype=np.int) </code></pre> <p>...
<p>Here's one alternative way. With <code>x</code>, <code>idx</code> and <code>K</code> defined as in your question:</p> <pre><code>indices = (idx[:,None] + K.shape[1]*idx).ravel('f') np.add.at(K.ravel(), indices, x.ravel()) </code></pre> <p>Then we have:</p> <pre><code>&gt;&gt;&gt; K array([[ 1., 2., 0., 0.], ...
python|arrays|numpy|multidimensional-array
3
3,552
31,212,141
How to resample a df with datetime index to exactly n equally sized periods?
<p>I've got a large dataframe with a datetime index and need to resample data to exactly 10 equally sized periods.</p> <p>So far, I've tried finding the first and last dates to determine the total number of days in the data, divide that by 10 to determine the size of each period, then resample using that number of day...
<p>Here is one way to ensure equal-size sub-periods by using <code>np.linspace()</code> on <code>pd.Timedelta</code> and then classifying each obs into different bins using <code>pd.cut</code>.</p> <pre><code>import pandas as pd import numpy as np # generate artificial data np.random.seed(0) df = pd.DataFrame(np.rand...
python|pandas
1
3,553
31,099,781
Apply curve_fit within a loop
<p>as indcated, I have a problem with fitting a function to data within a loop. This is a groupby object out of a dataframe. This groupby object has the following structure:</p> <pre><code> f [MHz] T [K] Rs 0 400 1.75 13.472493 1 400 2.00 14.054298 2 400 2.25 14.900821 3 400 2.50 16.453007 4 ...
<p>It sounds like <code>T</code> and <code>RsT</code> are NumPy arrays with a <em>non-object dtype</em>. Trying to assign an array of values to one cell of <code>T</code> raises the ValueError you are seeing:</p> <pre><code>In [117]: T = np.zeros(3) In [118]: T[0] = np.arange(10) ValueError: setting an array element ...
python|pandas
0
3,554
67,405,300
None of ['date'] are in the columns
<p>I'm trying to plot some graphs with numpy and plotly. I'm getting the data from a csv file containing all the trends that I need. I want to plot and analyze the values contained in columns 1-80 along the timeframe (&quot;Date&quot;) Here's the script I've written to do that.</p> <pre class="lang-py prettyprint-overr...
<ul> <li>By default <code>pd.read_csv</code> use a default value for <code>sep=','</code></li> <li>In this case use <code>sep=';'</code> when using <code>pd.read_csv</code>, since the value separator is <code>;</code></li> <li>Since you have set <code>Date</code> column as index using <code>ztec=ztec.set_index('Date')<...
pandas|numpy
1
3,555
67,357,062
pandas extract array to columns
<p>How can the array (the length of the array is constant for all elements in the series) be extracted into columns efficiently?</p> <pre><code>import pandas as pd d = pd.DataFrame({'foo':\[1,2,3\], 'bar':\[\[1,1,1\], \[2,2,2\], \[3,3,3\]\]}) d][1]][1] </code></pre> <p><a href="https://i.stack.imgur.com/DOf7F.png" rel=...
<p>How about this:</p> <pre><code>&gt;&gt;&gt; d.join(pd.DataFrame(d['bar'].to_list(), columns=['bar_1', 'bar_2', 'bar_3'])) foo bar bar_1 bar_2 bar_3 0 1 [1, 1, 1] 1 1 1 1 2 [2, 2, 2] 2 2 2 2 3 [3, 3, 3] 3 3 3 </code></pre> <p>You convert the <code>...
python|arrays|pandas|numpy|apply
5
3,556
67,338,354
Why does installing Tensorflow with conda ruin matplotlib?
<p>Starting from a new anaconda environment, it looks like this (summarized, not a full paste):</p> <pre><code>[myenv]$ python Python 3.8.8 ... &gt;&gt; import matplotlib.pyplot as plt &gt;&gt; [myenv]$ conda install tensorflow-gpu ... [myenv]$ python &gt;&gt; import tensorflow &gt;&gt; tensorflow.__version__ '2.4.1'...
<p>Do you have the complete traceback? Based on the Error you posted, it seems like its a dependency issue on the sip module. I'll recommend using you own virtualenv instead of anacondas.</p> <p>FOR CREATING YOUR OWN VIRTUALENV:<br /> open terminal<br /> go to the directory you want your project to be<br /> pip install...
python|tensorflow|matplotlib|anaconda|conda
0
3,557
67,350,036
Transform DataFrame of Dataframe into Single DataFrame Selecting only Some Columns Python
<p>I have the next Json File:</p> <pre><code>exchangeInfo = { &quot;timezone&quot;: &quot;UTC&quot;, &quot;serverTime&quot;: 1565246363776, &quot;rateLimits&quot;: [], &quot;exchangeFilters&quot;: [], &quot;symbols&quot;: [ { &quot;symbol&quot;: &quot;ETHBTC&quot;, &q...
<p>To get columns from only &quot;PRICE_FILTER&quot; and &quot;LOT_SIZE&quot; filters, try:</p> <pre><code>df = pd.json_normalize(exchangeInfo[&quot;symbols&quot;]) df = pd.concat( [ df, df.pop(&quot;filters&quot;) .apply( lambda x: dict( i for d i...
python|pandas|dataframe|binance
2
3,558
67,341,551
Highlight data based on a condition using Python Pandas and write it back to same .xls file
<p>I have a sample dataset, I want to</p> <ol> <li>Highlight the cell and add a comment column with comment &quot;Null/Blank in 'Item' column&quot;</li> <li>Highlight the cell and a add a comment column with comment &quot;presence of '_' in 'Store' Column&quot;</li> <li>Highlight the cell and add a comment column with ...
<p>Input data:</p> <pre><code>import pandas as pd import io df = pd.read_csv(io.StringIO(&quot;&quot;&quot;Store;Item;Category\nStore A;;Fruits\nStore A;Apple_;Fruits\nStore A;Orange;Fruits\nStore A;Banana;Fruits\nStore_B;Books;Stationary\nStore B;Pen;Fruits\nStore_B;Pencil;Fruits\nStore B;Glue;Stationary\nStore B;Era...
python|excel|pandas|dataframe
0
3,559
67,275,896
Python program freezes my computer when try to read CSV files with only 200k rows data
<p>I am a beginner in Python and I am facing a problem. I would like a user to select a CSV file to be read-in. In the case that the program cannot locate the file or handle the condition, it should default to an error.</p> <p>I have successfully implemented this solution for small file sizes (&lt; 50000 rows) but when...
<p>You are trying to take all file at once. But your memory isn't enough for that as you saying.</p> <p>So you need to process data little by little.</p> <p>Here is a good and simple example: <a href="https://stackoverflow.com/a/43286094/7285863">https://stackoverflow.com/a/43286094/7285863</a></p>
python|pandas|dataframe|csv|bigdata
-1
3,560
34,446,158
Dates to Durations in Pandas
<p>I feel like this should be done very easily, yet I can't figure out how. I have a <code>pandas</code> <code>DataFrame</code> with column <strong>date</strong>:</p> <pre><code>0 2012-08-21 1 2013-02-17 2 2013-02-18 3 2013-03-03 4 2013-03-04 Name: date, dtype: datetime64[ns] </code></pre> <p>I want to...
<p><code>Timedeltas</code> are useful here: <a href="http://pandas.pydata.org/pandas-docs/stable/timedeltas.html" rel="nofollow noreferrer">(see docs)</a></p> <blockquote> <p>Starting in v0.15.0, we introduce a new scalar type Timedelta, which is a subclass of datetime.timedelta, and behaves in a similar manner, but al...
python|pandas|timedelta
6
3,561
59,991,390
Pandas value_counts returning multiple lines for the same value
<p>Running into an issue with Pandas where my dataframe value_counts call is returning multiple lines for the same values. Instead of grouping all "True" values and all "False" values, it's splitting them into 4 groups.</p> <p>Here's my code:</p> <pre><code>import pandas as pd filepath=r"C:\Users\09.41.csv" df = pd...
<p>Check your values data type. Some of the rows may be string and some of them may be bool. For example:</p> <pre><code>[True,'True','False',False,False] </code></pre> <p>If that's the case, change them all to bool and then count the values:</p> <pre><code>df.Finished.apply(lambda x: 'True' in x if type(x)!= bool e...
python|python-3.x|pandas|csv
2
3,562
59,951,312
Pandas equivalent to dplyr dot
<p>I am sorry for pretty heavy explanation, but hope you will get the idea.</p> <p>I'm R user and I find tidyverse capabilities in data wrangling really powerful. But recently I have started learning Python, and in particular pandas to extend my opportunities in data analysis. Instinctively I'm trying to do things in ...
<p>In Pandas, run the chain of two <code>assign</code> calls but do so in any way that does not rely on <em>original</em> data frame context such as with <code>DataFrame.apply</code> call. Below uses a list comprehension equivalent across index values:</p> <pre><code>test_df = pd.DataFrame({'group': np.repeat([1,2,3],...
python|r|pandas
2
3,563
60,171,887
Is it possible to train with tensorflow 1 using float16?
<p>Currently train keras on tensorflow model with default setting - float32.</p> <p>Post training the network is quantized: cast weights to float16. This improves performance by ~x3 while keeping the same accuracy.</p> <p>I was trying to train from start using float16 and failed miserably. I cannot find any link that...
<p><a href="https://docs.nvidia.com/deeplearning/sdk/mixed-precision-training/index.html#faq-tf" rel="nofollow noreferrer">Automated Mixed Precision</a> from NVidia might be a way to go. </p> <p>From what I've gathered since <code>1.14</code> it is (was) supported in the upstream. All you would have to do is wrap your...
python|tensorflow|precision|keras-rl
2
3,564
60,329,503
Listify indices according to column groupby
<p>My question is similar to "<a href="https://stackoverflow.com/questions/22219004/grouping-rows-in-list-in-pandas-groupby">grouping rows in list in pandas groupby</a>", but what is to be listified is the index, not just another column.</p> <p>I know I can turn the index into just another column with <code>reset_inde...
<p>Use a list comprehension to iterate through the groups, and create a new dataframe</p> <pre><code>(pd.DataFrame([(name,group.index.tolist()) for name, group in df.groupby('a')], columns=['name','index']) ) name index 0 A [0, 1] 1 B [2, 3, 4] 2 C [5] </code></pre>
pandas|pandas-groupby
1
3,565
60,162,029
How can hide bars that does not have values in matplotlib bar plots
<p>I have a code that plots the total transactions per months. The dataset doesn't include all the months (Only from 10 to 4). Yet when I plot it, it still includes the months from 5 to 9 (with, of course, no bars). I want to hide those as they are not even part of the dataset. </p> <p>here is what I get: </p> <p><a ...
<p>The easiest way might be casting your <code>month</code> to <code>str</code> to avoid <code>matplotlib</code> filling up the missing numbers:</p> <pre><code>plt.bar(months_unique.astype(str), df_month['Transaction']) ... </code></pre> <p>Or simply let <code>pandas</code> handle the plotting for you instead:</p> <...
python|pandas|matplotlib
0
3,566
60,068,282
Tensorflow Object Detection AttributeError: module 'tensorflow._api.v1.compat' has no attribute 'v2'
<p>Currently running TF 1.13.2</p> <p>I'm trying to train my own object detection model. After trying to run this command:</p> <pre><code>python model_main.py --logtostderr --model_dir=training/ --pipeline_config_path=traini ng/faster_rcnn_inception_v2_pets.config </code></pre> <p>I get this error:</p> <pre><code>T...
<p>EDIT: from experience you are using a TF2 designed model in a TF1 application.</p> <p>Did you clone the models from Github? The repository is based on the latest TF</p> <p>You can use the models designed for 1.13 specifically: <a href="https://github.com/tensorflow/models/archive/v1.13.0.zip" rel="nofollow norefer...
python|windows|tensorflow
1
3,567
65,107,049
Installing packages in pycharm
<p>I'm kinda new to programming, and this is one of my first projects, a data science project.<br /> I am using PyCharm and I need to install numpy and pandas (and probably many others later).<br /> But I can't manage to download any package.</p> <p><a href="https://i.stack.imgur.com/hdUxr.png" rel="nofollow noreferrer...
<p>As discuss in comments : Pycharm 2020.2.4 is bugged with pip install, update to 2020.2.5 (and probably next versions in the future) resolve the issue.</p>
python|numpy|pycharm|package
0
3,568
50,213,201
How can one initialize data for a contour plot using a function that takes one input and outputs a scalar value?
<p><strong>NOTE:</strong> The post looks longer than it ought to because of docstrings and an array consisting of 40 datetimes.</p> <p>I have some time-series data. For examples sake, let's say I have three parameters, each consisting of 40 data points: datetimes (given by <code>dts</code>), speed (given by <code>vobs...
<p>If I understood your idea correctly then this should be what you need. However I needed the following packages:</p> <pre><code>import numpy as np import matplotlib import matplotlib.pyplot as plt from matplotlib.mlab import griddata import pandas as pd </code></pre> <p>First the required values are stored in three...
python-3.x|numpy|matplotlib|contour|scalar
1
3,569
49,973,180
Confused about tensorflow timeline
<p><a href="https://i.stack.imgur.com/XPj5Q.png" rel="nofollow noreferrer">enter image description here</a></p> <p>I think /device:GPU:0 and /job:localhost/replica:0/task:0/device:GPU:0 denote the same thing, but why their timelines are different? For example, the blue Conv2d of /device:GPU:0 is later than /job:localh...
<p><code>stream:all</code> indicates the computation itself happening. <code>/job:localhost/replica:0/task:0/device:GPU:0</code> are just the requests being made to enqueue kernels.</p> <p>See: <a href="https://github.com/tensorflow/tensorflow/issues/1824#issuecomment-244251867" rel="nofollow noreferrer">https://githu...
tensorflow
0
3,570
49,797,977
Pandas - Reshape
<p>Can you help me to reshape a Pandas DataFrame from this:</p> <pre><code>df = pd.DataFrame({ 'Clasif1': [np.NaN, np.NaN, 'PRE', 'POST'], 'Currency': [np.NaN, np.NaN, 'LC', 'USD'], 'Unnamed: 1': ['A','01/01/2018',1,7], 'Unnamed: 2': ['A','02/01/2018',2,8], 'Unnamed: 3': ['A','03/01/2018',3,9], 'Unnamed: 4': ['B','01/...
<p>This is more like a customize solution , but if you can make sure the data is like this structure , you can using <code>stack</code> </p> <pre><code>s=df.iloc[:,2:].T.set_index([0,1]).stack() s=s.to_frame('V').reset_index(level=[0,1]) s=s.join(df.iloc[:,:2]).sort_values([0,1]) s Out[226]: 0 1 V Clas...
python|pandas|transform|reshape
2
3,571
49,948,876
GeoPandas: How to obtain bounding boxes for every geometry in a geodataframe
<p>I am using GeoPandas in python and have a valid GeoDataframe of polygons. </p> <pre><code>0 POLYGON Z ((68.70999999999999 623.1 0, 35.71 6... 1 POLYGON Z ((221.33 645.02 0, 185.7 640.33 0, 1... 2 POLYGON Z ((150.3 650 0, 160.9 650 0, 150.58 6... </code></pre> <p>I want to obtain a new dataf...
<p>You can also try the following</p> <pre><code># remove empty geometry valid_geom = gdf[gdf.geometry.map(lambda z: True if not z.is_empty else False)] # get the bounds of each geometry valid_geom.geometry.map(lambda z: z.exterior.xy) # or in one line gdf[gdf.geometry.map(lambda z: True if not z.is_empty else False)]...
geospatial|shapely|geopandas
2
3,572
63,990,844
How to generate values based on conditions for new columns?
<p>I have the following data frame:</p> <pre><code>Hotel_id Month_Year Chef_Id Chef_is_masterchef Transition 2400188 February-2018 4597566 1 0 2400188 March-2018 4597566 1 0 2400188 April-2018 4597566 1 0 2400188 ...
<p>IIUC, use <code>pandas.DataFrame.groupby.transform</code> with <code>numpy.arange</code> and <code>numpy.argmax</code>:</p> <pre><code>df[&quot;Var&quot;] = df.groupby(&quot;Chef_Id&quot;)[&quot;Transition&quot;].transform(lambda x: np.arange(x.size) - np.argmax(x)) print(df) </code></pre> <p>Output:</p> <pre><code>...
python|pandas|dataframe|pandas-groupby
2
3,573
64,112,510
how to consolidate lots of series data? to make another dataframe. using stack function
<p>I'd like to consolidate dataframe but I don't know how to upload dataframe here so I just remain link below.<br /> The data(original data on my spreadsheet)that I want to consolidate is form of series or dataframe.</p> <p>Part#: consists of 8~13 character set (alphabet and number mixed)<br /> Description: always rig...
<pre><code>import pandas as pd # create dataframe df = pd.DataFrame({ &quot;a&quot; : [ 'A2C02158300', 'D REC/BAS16-03W,100V,250mA,SOD323,0s,SMD', 'D201,D206,D218,D219,D222,D302,D308,D408,', 'D409,D501,D502,D505,D506,D507,D508', 'A2C02250500', 'T BIP/PUM...
python|pandas|stack|character|apply
1
3,574
63,816,321
Why Pytorch autograd need another vector to backward instead of computing Jacobian?
<p>To perform <code>backward</code> in Pytorch, we can use an optional parameter <code>y.backward(v)</code> to compute the Jacobian matrix multiplied by <code>v</code>:</p> <pre><code>x = torch.randn(3, requires_grad=True) y = x * 2 v = torch.tensor([0.1, 1.0, 0.0001], dtype=torch.float) y.backward(v) print(x.grad) <...
<p>When you call backward() PyTorch udpdates the <code>grad</code> of each learnable parameter with the gradient of some loss function <code>L</code> w.r.t to that parameter. It has been designed with Gradient Descent [GD] (and its variants) in mind. Once the gradient has been computed you can update each parameter wit...
python|optimization|pytorch|backpropagation|automatic-differentiation
3
3,575
46,655,518
How to one hot encode a large dataframe when multiple columns contain the same values?
<p>The title essentially captures my problem. </p> <p>I have a dataframe and multiple columns have values such as <code>[0,1]</code> and if I were to go and one hot encode the df, I'd have multiple columns with the same name. </p> <p>The tedious solution would be to manually create unique columns but I have 58 column...
<p>You are probably already using <code>pandas.get_dummies</code>? If not, this function converts categorical columns into multiple indicator columns (one hot encoding).</p> <p>There is a 'prefix' argument to this function which exists specifically for your case. This can be a list of strings (length must be equal to ...
python|pandas|one-hot-encoding
1
3,576
46,691,873
Datashader - Can it work with timestamp on x-axis without converting it to milliseconds as shown in an example
<p>I am going through a notebook available to plot time series using data shader and noticed that they have converted the time series vales to 'ms' and then used these values for x-axis</p> <p><a href="https://anaconda.org/jbednar/tseries/notebook" rel="nofollow noreferrer">https://anaconda.org/jbednar/tseries/noteboo...
<p>Bokeh's low level, foundational representation of datetime values is "floating point milliseconds since epoch". So sending that is always an option. However, Bokeh can recognize and generally convert most common datetime data types automatically: numpy datetime arrays, Pandas datetime indices and series, python date...
python|pandas|numpy|bokeh|datashader
1
3,577
32,751,077
Splitting & Moving cell in Pandas
<p>I have a slight problem with my pandas DataFrame. </p> <p>As the image shows, the first row has <code>released_date</code> as "Released 2006" while all other values for the same column have the format "Released MMM DD". </p> <p>I would like to split the first cell under <code>released_date</code> to "Released" and...
<p>You can use the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.strings.StringMethods.extract.html" rel="nofollow"><code>str.extract</code></a> method to extract the year:</p> <pre><code>In [11]: df["release_date"].str.extract("(\d{4})") Out[11]: 0 2006 1 2014 2 2015 3 2015 Na...
python|pandas
0
3,578
32,996,137
Selecting a subset of values in python
<p>I have a pandas dataframe, df, which contains a feature ('alpha') which is a list of letters {'A','B',...,'G'}</p> <p>I'd like to select from df all rows which belong to a subset of this feature, say {'A','B','C'}.</p> <p>What's the most 'pythonic' way to do this? </p> <p>I was thinking something along the line...
<p>I think you want to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html#pandas.Series.isin" rel="nofollow"><code>isin</code></a> to test for membership, example:</p> <pre><code>In [79]: subset = {'a','b','c'} df = pd.DataFrame({'a':list('abasbvggcgasgfdasgcdce')}) df[df['a'].i...
python|pandas
1
3,579
38,769,935
Scipy Non-central Chi-Squared Random Variable
<p>Consider a sum of <code>n</code> squared iid normal random variables <code>S = sum (Z^2(mu, sig^2))</code>. According to <a href="https://mathoverflow.net/questions/89779/sum-of-squares-of-normal-distributions">this question</a>, <code>S / sig^2</code> has a <a href="https://en.wikipedia.org/wiki/Noncentral_chi-squ...
<p>The problem is in the second sentence of the question: <em>"<code>S / sig^2</code> has a noncentral chi-squared distribution with degrees of freedom = <code>n</code> and non-centrality parameter = <code>n*mu^2</code>."</em> That non-centrality parameter is not correct. It should be <code>n*(mu/sig)^2</code>.</p> ...
python|numpy|scipy
3
3,580
38,936,016
Keras - How are batches and epochs used in fit_generator()?
<p>I have a video of 8000 frames, and I'd like to train a Keras model on batches of 200 frames each. I have a frame generator that loops through the video frame-by-frame and accumulates the (3 x 480 x 640) frames into a numpy matrix <code>X</code> of shape <code>(200, 3, 480, 640)</code> -- (batch size, rgb, frame heig...
<blockquote> <p>After the first epoch is complete (after the model logs batches 0-24), the generator picks up where it left off</p> </blockquote> <p>This is an accurate description of what happens. If you want to reset or rewind the generator, you'll have to do this internally. Note that keras's behavior is quite us...
python|tensorflow|generator|keras
11
3,581
38,676,558
How to get the Average of a specific category via Python
<p>I was wondering how I could calculate the average of a specific category via Python? I have a csv file called demo.csv</p> <pre><code> import pandas as pd import numpy as np #loading the data into data frame X = pd.read_csv('demo.csv') </code></pre> <p>the two columns of interest are the <code>Category</code> an...
<p>You can restrict your dataframe to the subset of the rows you want(<code>Category=2</code>), followed by taking mean of the columns corresponding to <code>Totals</code> column as follows:</p> <pre><code>df[df['Category'] == 2]['Totals'].mean() 2745.5 </code></pre>
python|csv|pandas|average
3
3,582
63,055,541
Finding closest points to a multidimensional data point?
<p>I have a dataset that gives the values of some songs, ie something that looks like:</p> <pre><code> acousticness danceability energy instrumentalness key liveness loudness 0 0.223 0.780 0.72 0.111 1 0.422 0.231 1 0.4 0.644 0.88 0.555 0.5 0....
<p>You can use <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.euclidean.html#scipy.spatial.distance.euclidean" rel="nofollow noreferrer">scipy.spital.distance.euclidean</a> to calculate the distance between two multidimetional points.</p> <p>In your case e.g.</p> <pre class="lang-p...
python|pandas|dataframe|dimension
0
3,583
63,166,570
Pandas: Convert a JSON column with multiple rows into multiple dataframe rows
<p>I have a dataframe with two columns: <code>countries</code> and <code>year</code>. The <code>countries</code> column is JSON in the form of:</p> <pre><code>[{'continent': 'europe', 'country': 'Yugoslavia', 'income': None, 'life_exp': None, 'population': 4687422}, {'continent': 'asia', 'country': 'United K...
<p>should add <code>ignore_index=True</code> argument in <code>explode</code> function to make sure the following <code>join</code> is not messed up.</p> <pre class="lang-python prettyprint-override"><code>df = pd.DataFrame(data).explode('countries', ignore_index=True) df = df.join(pd.json_normalize(df.pop('countries')...
python|json|pandas
0
3,584
68,013,311
Converting one column of a dataframe from minute to hhmm and hh:mm format in python
<p>I have a data frame named 'df' where the column 'A' contains the time from 0 to 1440 minutes in a day. I want to add extra columns having the same time in hhmm format and hh:mm format. How can I do that in python?</p>
<p>You can first convert values to timedeltas:</p> <pre><code>df = pd.DataFrame({'A':[10,20,1440, 0]}) df['A'] = pd.to_timedelta(df['A'], unit='min') print (df) A 0 0 days 00:10:00 1 0 days 00:20:00 2 1 days 00:00:00 3 0 days 00:00:00 </code></pre> <p>For formating use:</p> <pre><code>def f(x): ts ...
python|pandas|dataframe|datetime
0
3,585
31,998,780
Removing rows based off of a value in a column (pandas)
<p>I'm trying to remove row values if the column 'Comment' has 'Bad Process' in it. </p> <pre><code> ID Name Comment 0 W12D0 Fine 1 W12D0 Bad Process 2 W12D0 What 3 W12D4 Fine 4 W12D5 Random 5 W12D5 Fine .. ... ... </...
<p>You can use <code>.loc</code> to get the <code>ID Name</code> of all rows which have 'Bad Process' in the Comments column.</p> <p>You then use <code>.loc</code> again, but this time as a mask to filter out the bad records. The tilda (~) is a negation, so it finds rows in the dataframe where the ID Name is NOT in t...
python|pandas|indexing|row|dataframe
2
3,586
31,838,044
Is there a way to write two (or more) dataframes to one excel spreadsheet?
<p>it would help me produce output that was a lot neater and a little more 'human-like' if I could use pandas and xlsxwriter in a way that would stack two dataframes, one on top of the other, on the same sheet of the Excel spreadsheet I am outputting.</p> <p>Pls note the data of the two dataframes is related but diffe...
<p>Yes, it's very much possible.</p> <p>You will have to build the excel file using xlsxwriter and keep track of the current cell as you write.</p> <p>Here is some pseudo code/syntax (I use xlsxwriter as an extension of Pandas):</p> <pre><code>wb = pd.ExcelWriter(file) tab = wb.sheets["My Tab"] row, column = 9, 1 df...
python|excel|pandas|dataframe
2
3,587
31,996,872
Getting the date of the last day of this [week/month/quarter/year]
<p>Is there any way to get the date (a <code>datetime</code>, <code>pd.Timestamp</code> or equivalent) of the last day of this [week/month/quarter/year] with <code>datetime</code>, <code>pandas</code> or other date &amp; time utils?</p>
<p>Using <code>datetime</code> only.</p> <pre><code>&gt;&gt;&gt; d = datetime.date.today() </code></pre> <p>Last day of week:</p> <pre><code># This was wrong earlier. &gt;&gt;&gt; d + datetime.timedelta(days=5 - d.weekday()) datetime.date(2015, 8, 15) </code></pre> <p>Last day of month:</p> <pre><code>&gt;&gt;&gt;...
python|python-3.x|pandas
7
3,588
41,521,962
Bazel error: "No test targets were found, yet testing was requested"
<p>I have a small assignment where I used TensorFlow to create music:</p> <p><a href="https://github.com/tensorflow/magenta" rel="nofollow noreferrer">https://github.com/tensorflow/magenta</a></p> <p>When I run the code <code>--- bazel test //magenta:all</code> I get the following error:</p> <pre> WARNING: /home/adm...
<p>When you run</p> <pre><code>bazel test magenta:all </code></pre> <p>This means "execute all *_test rules defined in file magenta/BUILD. When I look at that file, there are no tests defined there. <a href="https://github.com/tensorflow/magenta/blob/master/magenta/BUILD" rel="noreferrer">https://github.com/tensorflo...
tensorflow|bazel|magenta
6
3,589
41,669,496
Counting in dataframe
<p>I have a dataframe that looks as follows </p> <pre><code>A,B,C,D X1,desc,may 1, 1 X2,desc, june 5, 1 Y,desc, dec 8, 2 Y,desc, jan 4, 3 </code></pre> <p>I want to look at X1, X2, and Y. And sum so that the dataframe looks as follows: </p> <pre><code>A,B X1,1 X2,1 Y,5 </code></pre> <p>So for all instances of X1...
<p>If the column to group by is set as the index as is the case here:</p> <pre><code> B C D A X1 desc may 1 X2 desc june 1 Y desc dec 2 Y desc jan 3 </code></pre> <p>Simply use a group by index as below:</p> <pre><code>df1.groupby([df1.index]).D.sum...
pandas|dataframe|count
0
3,590
61,194,194
pandas to numpy matrix conversion drops columns
<p>I have the following data frame, but need it as a numpy array to pass into Keras. I need to preserve the month, year, shop_id and item_id columns, but the numpy array drops them and only keeps the item_category_id and avg_item_price.</p> <pre><code>month year shop_id item_id item_category_id avg_item_price 01 2...
<p>You those columns are used as the indices in pandas, you have to reset them:</p> <pre><code>df = df.reset_index() </code></pre>
pandas
1
3,591
68,734,504
Boxplot by two groups in pandas
<p>I have the following dataset:</p> <pre><code>df_plots = pd.DataFrame({'Group':['A','A','A','A','A','A','B','B','B','B','B','B'], 'Type':['X','X','X','Y','Y','Y','X','X','X','Y','Y','Y'], 'Value':[1,1.2,1.4,1.3,1.8,1.5,15,19,18,17,12,13]}) df_plots Group Type ...
<p>We can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.boxplot.html" rel="nofollow noreferrer"><code>groupby boxplot</code></a> to create subplots per <code>Group</code> and then separate each <code>boxplot</code> by <code>Type</code>:</p> <pre><code>fig, axes = plt.sub...
python|pandas|matplotlib|boxplot
4
3,592
68,514,274
Parameters for LSTM with CNN in a sequential data
<p>I am doing a classification problem with ECG data. I built a LSTM model but the accuracy of the model is not quiet good. Hence, I am thinking to implement it with CNN. I am planning to pass the data from CNN, then passing the output from CNN to LSTM. Howver, I have noticed that CNN is mostly used in Image classifica...
<p>Well, that's yours to define, it's the actual architectural decision your need to take to construct your model. The following is not a solution to your question, however, this might give you some ideas.</p> <ul> <li><p>You could pass each timestep through the CNN and retrieve a sequence of feature vectors correspond...
parameters|pytorch|conv-neural-network|lstm
1
3,593
68,581,656
Issues with conditionals in pandas
<p>I have this <code>df</code>:</p> <pre><code> CODE DATE MONTH_DAY PPTOT SECTOR_1 0 472606FA 2001-01-01 01-01 0.0 SN 1 472606FA 2001-01-02 01-02 0.0 SN 2 472606FA 2001-01-03 01-03 0.7 SN 3 472606FA 2001-01-04 01-04 NaN SN 4...
<p>The <code>&amp;</code> operator has higher precedence than <code>&lt;=</code>, <code>==</code>, etc., so you have to add parentheses around the second condition as well.</p> <pre><code>df.loc[(df['PPTOT'] &lt;= 0) &amp; (df['SECTOR_1']=='CS'), 'PPTOT'] = np.nan </code></pre>
python|pandas
2
3,594
68,665,191
Change numeric values in rows of CSV if string in same row has certain value
<p>I have a <em><strong>csv</strong></em> that looks like below with up to <em><strong>15000 lines</strong></em>.<br> The numeric values of <code>Start</code> and <code>End</code> are between 0 and 300.<br> I am looking for a way to parse through the file, search for rows starting with <code>white</code>, then check th...
<pre><code>$ awk 'BEGIN{FS=&quot; *, *&quot;; OFS=&quot;, &quot;; n=150} $1==&quot;white&quot;{ for (i=2; i&lt;NF; i++) $i+=($i&gt;n ? -n : n) } 1' file Color, Start, End white, 150, 151, black, 23, 150, black, 150, 24, white, 174, 2, black, 152, 25, black, 25, 154, black, 154, 81, white, 249, 70, </code></pre>
python|pandas|bash|csv|awk
0
3,595
68,694,047
PyTorch Lightning functools.partial error
<p>I'm using a combination of PyTorch Forecasting and PyTorch Lightning, and running into an odd error. Some code below.</p> <pre><code>batch_size = 128 train_dataloader = training.to_dataloader(train=True, batch_size=batch_size, num_workers=8) val_dataloader = validation.to_dataloader(train=False, batch_size=batch_siz...
<p>This ended up being caused by an issue with a recent pandas upgrade. Rolling back to 1.2.5 resolved the issue.</p> <pre><code>pip install --upgrade pandas==1.2.5 </code></pre> <p>Details on the problem in the link below.</p> <p><a href="https://github.com/pandas-dev/pandas/issues/42748" rel="nofollow noreferrer">ht...
python|pytorch|pytorch-lightning
3
3,596
68,536,204
Extract value of each column and store in a list/dictionary for each index value
<p>I have a dataframe with 5 columns. I want to look through 3 of them and store in dict or list (whichever is more efficient) the values of each of the 5 columns</p> <p>Example:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th></th> <th>A</th> <th>B</th> <th>C</th> <th>D</th> <th>E</th> </t...
<p>Try:</p> <pre><code>index_1, index_2, index_3 = [list(row) for row in df[[&quot;A&quot;, &quot;B&quot;, &quot;E&quot;]].values] </code></pre>
python|pandas
2
3,597
68,729,622
How to assign column heading to corresponding cell values?
<p>I'm just learning Python and for my first project I am trying to re-format a excel table that I can use on GIS. The Table have many columns with x for each corresponding records. I need to assign (replace the x) with the column names and concatenate all rows separated by commas. I was told that Pandas is a very good...
<pre><code>data_dict = { 'Species_ID': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'Habitat_A': ['X', '', 'X', 'X', '', 'X', 'X', '', 'X', ''], 'Habitat B,C,&amp;D': ['X', '', 'X', 'X', '', 'X', 'X', '', 'X', ''], 'Habitat_E': ['', 'X', '', 'X', 'X', '', 'X', 'X', '', 'X'], } df = pd.DataFrame.from_dict(data_dict...
python|pandas
2
3,598
36,600,465
converting pandas column to np 2d array
<p>I am adapting a pandas plotting example for my own data. I have a question on converting a pandas dataframe column to the correct shape (1 , 10). More specifically. the correct format is achieved with this code </p> <pre><code>z = np.random.rand(1, 10) </code></pre> <p>which produces this </p> <pre><code>array([[...
<pre><code>y = df['col_name'].as_matrix().reshape(1, len(df['col_name'])) </code></pre> <p>Yields:</p> <pre><code>array([[218584205, 55738338, 52152386, 37920152, 35472238, 32611026, 30268255, 26709195, 25979749, 24804423]]) </code></pre>
python-3.x|pandas|plot|dataframe
1
3,599
53,200,550
How to extract t[i,i,:] using tensorflow?
<p>For example:</p> <pre><code>t = tf.constant(np.array([[[1,2],[3,4]],[[5,6],[7,8]]])) # I want to extract h = [[1,2],[7,8]] </code></pre> <p>How to use tensorflow to do this? Thank you!</p>
<p>You can use <code>tf.gather_nd()</code>. It gathers slices from the last dimension given some indices. You can read more on that <a href="https://www.tensorflow.org/api_docs/python/tf/gather_nd" rel="nofollow noreferrer">here</a>.</p> <pre><code>import tensorflow as tf t = tf.constant(np.array([[[1,2],[3,4]],[[5,...
python|tensorflow
1