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
12,200
71,367,832
Turning Nan values into zeroes pandas Python
<p>I want to turn the <code>nan</code> values into zeroes and get the Expected Output.</p> <pre><code>import pandas as pd data = pd.DataFrame({'Symbol': {4: 'DIS', 5: 'DKNG', 6: 'EXC'}, 'Number of Buy s': {4: 1.0, 5: 2.0, 6: 1.0}, 'Number of Cover s': {4: nan, 5: 2.0, 6: nan}, 'Number of Sell s': {4...
<p>To replace all NaN values of a DataFrame with 0 -</p> <pre><code>df = df.fillna(0) </code></pre>
python|python-3.x|pandas|database|dataframe
1
12,201
52,431,352
Pandas Series resample + interpolate gives NaNs
<p><code>x</code> is a pandas series of float64 numbers on a DateTimeIndex</p> <p><code>x.head(20)</code> looks like this:</p> <pre><code>Timestamp 2018-05-03 15:05:31.864 1.799104 2018-05-03 15:05:31.993 1.080555 2018-05-03 15:05:32.145 1.374885 2018-05-03 15:05:32.963 1.264249 2018-05-03 15:05:33.529 ...
<p>IIUC:</p> <p>You want to interpolate with a union of the existing index along with the resampled index.</p> <pre><code>idx = pd.date_range(x.first_valid_index(), x.last_valid_index(), freq='100ms') </code></pre> <p>This is a cute way of getting the index</p> <pre><code>idx = x.asfreq('100ms').index </code></pre>...
python-3.x|pandas
2
12,202
52,333,531
Extract element by line starting with a specific character
<p>I'm currently working on this DataFrame python :<br> <img src="https://i.stack.imgur.com/JwXNK.png" alt="Extract data frame"></p> <p>The data-set has one column and n lines.</p> <p>I would like to extract specifics components of specifics line, for exemple : </p> <p><em>For each line i starting with 'n', store in...
<p>Create simple example:</p> <pre><code>d = pd.DataFrame({'a': ['aaaak', 'k jhs', 'anhdga', 'kjdhs']}) </code></pre> <p>You can use column.str and see a first letter:</p> <pre><code>data.a.str[0] </code></pre> <p><strong>out:</strong></p> <pre><code>0 a 1 k 2 a 3 k </code></pre> <p>And you can check ...
python|pandas|numpy|dataframe|data-cleaning
1
12,203
60,578,106
Can't manage use the function : predict() in tensorflow(keras)
<p><a href="https://stackoverflow.com/questions/60543640/cant-manage-to-use-the-model-predict-in-kerastensorflow/60543947?noredirect=1#comment107155611_60543947">This is a continuation to my lsat question</a></p> <p>I'm getting errors saying that something went wrong with the predict function, I tried reading about th...
<p>When I extracted data from my data base it was actually a 2d array, and when I built a vector it was 1d so the model didn't recognize the shape of it.</p> <p>changing predict(pe) to predict(pe[None]) did the job!</p> <p>credit to: <a href="https://stackoverflow.com/users/9393102/xdurch0">xdurch0</a> </p>
python|tensorflow|machine-learning|keras
0
12,204
60,746,988
python3 pandas move data into new columns if condition met
<p>If I have a dataframe:</p> <pre><code>names,individual ABC LLC, business John Smith, individual </code></pre> <p>How can I shift the names into a new column called 'businessname' if the 'individual' column='business'?</p> <p>Desired output:</p> <pre><code>names,individual,businessname null, business, ABC LLC Joh...
<p>There are probably several ways to move data into a column. One way particular to your problem is creating a column with selected data.</p> <p>The following code creates a dataframe with your data</p> <pre><code>import pandas as pd # Contruct dataframe # names,individual # ABC LLC, business # John Smith, individu...
python-3.x|pandas
1
12,205
60,627,303
Add dataframe and button to same sheet with XlsxWriter
<p>I am able to create an excel file with in one sheet the data from a data frame and in a second sheet a button to run a macro What I need is to have both the data from the dataframe than the button in the same sheet</p> <p>This is the code I found that I have tried to modify:</p> <pre><code>import pandas as pd impo...
<p>I know that you simply asked how to insert the button in the same sheet but i decided to check how the macros are working with xlsxwriter, so i wrote a complete tutorial on how to add a macro.</p> <p>1) Firstly we need to create manually a file which will contain the macro in order to extract it as a bin file and i...
pandas|xlsxwriter
2
12,206
60,694,853
How to use a 3rd dataframe column as x axis ticks/labels in matplotlib scatter
<p>I'm struggling to wrap my head around matplotlib with dataframes today. I see lots of solutions but I'm struggling to relate them to my needs. I think I may need to start over. Let's see what you think.</p> <p>I have a dataframe (ephem) with 4 columns - <strong>Time</strong>, <strong>Date</strong>, <strong>Altitude...
<p>This isn't by any means the cleanest piece of code but the following works for me:</p> <pre><code>import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.scatter(ephem.Azimuth, ephem.Altitude, marker='x', color='black', s=8) labels = list(ephem.Time) ax.set_xticklabels(labels) plt.show() </code></pre> <p>Here...
python|pandas|matplotlib
0
12,207
59,842,040
Pandas Function similar to SQL rank and partition
<p>I have the below data</p> <pre><code>ID DD DAYS VALUE 1 08-MAR-19 4 500 1 09-MAR-19 1 1500 2 13-MAR-19 0 0 </code></pre> <p>I want to select the maximum number of days like for ID 1 it will only return the row with 4. In SQL I use the below query</p> ...
<p>Here is another option using <code>loc</code> which is used for the old <code>select</code> function in pandas.</p> <pre><code>import pandas as pd data = {'id':[1,1,4],'DD':['08-MAR-19','09-MAR-19','13-MAR-19'],'DAYS':[4,1,0],'VALUE':[500,1500,0]} df = pd.DataFrame(data) df = df.loc[(df['id'] == 1) &amp; (df['DAYS...
python|sql|pandas|oracle
0
12,208
59,767,436
Adding a dynamic MultiFrame index
<p>a question which I'm not able to answer myself. I've created a dataframe containing tournament rankings. The dataframe is the result of a group action and looks like this:</p> <pre><code>d ={'games': {('A', 1, 'Hawks'): 6, ('A', 4, 'Eagles'): 6, ('B', 2, 'Sparrows'): 6, ('B', 3, 'Falcons'): 6, ('B', 5, ...
<p>Use <code>groupby</code> with <code>rank</code> with <code>ascending=False</code> to get rank for each group and then set index with <code>append=True</code> , then <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reorder_levels.html" rel="nofollow noreferrer"><code>reorder</code>...
python|pandas
1
12,209
61,641,466
I am returning a count from a column in a dataframe successfully, but I get NaN value when trying to import results into a column
<p>I am new to ArcGIS API for Python and I am trying to create a tool using Notebook in ArcGIS Pro 10.5, that will re-engineer a table (csv file). The dataframe is titled <strong>data_df</strong> I need to get a count of the amount of ages, per country, that occured in a particular age group (Under 1, 1-2yrs, 3-4yrs, 5...
<p>Consider creating a dictionary, which you can use to remap your values. Then use one-hot encoding.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame([ ['USA', 3, 'M'], ['USA', 5, 'F'], ['USA', 10, 'F'], ['Canada', 0, 'M'],['Canada', 1, 'M'], ['Canada', 9,...
pandas|jupyter-notebook|pandas-groupby|jupyter|arcgis
0
12,210
54,774,066
How to find unique combinations in one hot encoded dataframe?
<p>I have a dataframe called test that looks like this</p> <pre><code>+-------+---------+---------+---------+------------+ | | Term 1 | Term 2 | Term 3 | Final Exam | +-------+---------+---------+---------+------------+ | 1288 | 0 | 0 | 1 | 1 | | 1290 | 1 | 1 | 1 ...
<p>With <code>dot</code> and <code>value_counts</code></p> <pre><code>df.dot(df.columns+',').str[:-1].value_counts() Out[419]: Term1,Term2,Term3,FinalExam 6 Term3,FinalExam 3 Term2,Term3,FinalExam 1 dtype: int64 </code></pre>
pandas|apriori
2
12,211
49,740,247
Tensorflow MNIST Estimator: batch size affects the graph expected input?
<p>I have followed the TensorFlow MNIST Estimator tutorial and I have trained my MNIST model.<br> It seems to work fine, but if I visualize it on Tensorboard I see something weird: the input shape that the model requires is 100 x 784.</p> <p>Here is a screenshot: as you can see in the right box, expected input size is...
<p><code>tf.reshape</code> won't discard shape information for <code>-1</code> dimensions. That's just a shorthand for "whatever's left over":</p> <pre><code>&gt;&gt;&gt; import tensorflow as tf &gt;&gt;&gt; a = tf.constant([1.,2.,3.]) &gt;&gt;&gt; a.shape TensorShape([Dimension(3)]) &gt;&gt;&gt; tf.reshape(a, [-1, 3]...
python|numpy|tensorflow|mnist|tensorflow-estimator
4
12,212
67,602,060
How to print state of model in Federated learning
<p>I would like to print (before training) the state of model : with <code>print(state['model'])</code>, I found this error :</p> <pre><code>TypeError: 'ServerState' object is not subscriptable </code></pre>
<p><a href="https://www.tensorflow.org/federated/api_docs/python/tff/learning/framework/ServerState" rel="nofollow noreferrer"><code>tff.leraning.framework.ServerState</code></a> is a Python <a href="https://www.attrs.org/en/stable/" rel="nofollow noreferrer">attrs class</a>, whos fields are accessed via the <code>Inst...
tensorflow-federated|federated-learning
2
12,213
60,155,632
Tensorflow imports cause Heroku timeout (Django Python)
<p>I'm using Heroku (free) to try to deploy a relatively simple neural network I made using Django. The problem is that when I import tensorflow to load the saved model, tf takes longer than 30 seconds to import, causing my single web worker to timeout and kill the page load.</p> <p>Looking around on the internet, I f...
<p>It turns out that using python threading DID help get past the R12 heroku timeout, but I then had a confounding error: my Django <code>ALLOWED_HOSTS</code> setting did not have the correct localhost url listed to run the site.</p>
tensorflow|heroku
0
12,214
65,202,662
Fixing missing values in pandas dataframe
<p>I have dataframe with below columns:</p> <pre><code>STORE METHOD DIVISION PROB VALUEX 20 1 5 0.85 0.759069373 20 2 5 0.85 2.663386705 20 3 5 0.85 2.511800796 20 1 6 0.85 0.170134162 20 3 6 0.85 0.921435575 20 3 7 0.85 0.947311849 20 1 8 0.85 3.39451593...
<p>Let's try pivot, fill value and unstack:</p> <pre><code>x = df.pivot_table(index=['STORE','DIVISION','PROB'], columns=['METHOD'], values='VALUEX') means = x.mean(1) x = x.apply(lambda s: s.fillna(means)) x.stack().reset_index(name='VALUEX') </code></pre> <p>Output:</p> <pre><code> STORE DIVISION...
pandas|dataframe|pandas-groupby
0
12,215
65,410,017
How to return a value based on column value and Timestamp using user-defined function in pandas
<p>I have two dataframe, which I have joined. On the joined Dataframe, I'm writing a user-defined function where based on Timestamp and the value count of the column i need to return the value based on the condition mentioned below create a new column called &quot;Day_Sentiment&quot;. But I'm getting below error. Pleas...
<p>There Several issues with your code. To begin the variables bad, good, &amp; neut are Panda Series of different lengths containing string variables. You then attempt to evaluate perform several conditional tests for example <code>if ((bad&gt; good) &amp; (bad&gt; neut)</code> which generates your ValueError. I a...
python|python-3.x|pandas|dataframe|valueerror
0
12,216
65,349,544
Getting range of values from Pytorch Tensor
<p>I am trying to get a specific range of values from my pytorch tensor.</p> <pre><code>tensor=torch.tensor([0,1,2,3,4,5,6,7,8,9]) new_tensor=tensor[tensor&gt;2] print(new_tensor) </code></pre> <p>This will give me a tensor with scalars of 3-9</p> <pre><code>new_tensor2=tensor[tensor&lt;8] print(new_tensor2) </code></p...
<p>You can use <code>&amp;</code> operation,</p> <pre><code>t = torch.arange(0., 10) print(t) print(t[(t &gt; 2) &amp; (t &lt; 8)]) </code></pre> <p>Output is,</p> <pre><code>tensor([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.]) tensor([3., 4., 5., 6., 7.]) </code></pre>
pytorch|tensor
1
12,217
65,223,561
Append csv files in multiple folders into one dataframe
<p>I have csv files, called &quot;<code>toyexample</code>&quot; in multiple subfolders. I want to append all csv files called <code>toyexample</code> in all the subfolders. The path folders are as follows:</p> <pre><code>C:/Users/xxx/Dropbox/College/Project1/2005Q1/ C:/Users/xxx/Dropbox/College/Project1/2005Q2/ ..... ....
<p>Use <code>glob</code> with <code>recursive=True</code> to find the paths of all files named <code>toyexample.csv</code> in your file tree.</p> <pre><code>glob.glob(&quot;**/toyexample.csv&quot;, recursive=True) </code></pre> <p>Will give you a list of paths starting in your current working directory for each <code>t...
python|python-3.x|pandas|csv
2
12,218
65,480,545
How to break and convert header into multiheader in pandas? This is a focused question
<div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Names</th> <th>ABCBaseCIP00</th> <th>ABCBaseCIP01</th> <th>ABCBaseCIP02</th> <th>ABC1CIP00</th> <th>ABC1CIP01</th> <th>ABC1CIP02</th> <th>ABC2CIP00</th> <th>ABC2CIP01</th> <th>ABC2CIP02</th> </tr> </thead> <tbody> <tr> <td>X</td> <td>1</td> <td>2<...
<p>Something like this may do it:</p> <pre><code>import pandas as pd df = pd.DataFrame({'ABCBaseCIP00': [1, 1, 1], 'ABCBaseCIP01': [2, 2, 2], 'ABCBaseCIP02': [3, 3, 3], 'ABC1CIP00': [4, 4, 4], 'ABC1CIP01': [5, 5, 5], 'ABC1CI...
python|pandas|dataframe|header|multi-index
1
12,219
50,000,557
Pandas Series - How to use functions in a nested way?
<p>When I tried to use simple multiplication on pandas Series, I get index to index result like this:</p> <pre><code>pd.Series([1, 2, 3]) * pd.Series([4, 5, 6]) &gt;&gt;&gt; 0 4 1 10 2 18 </code></pre> <p>I want to do this operation in a "nested" way like this:</p> <pre><code>&gt;&gt;&gt; 0 4 ...
<p>Use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.outer.html" rel="nofollow noreferrer"><code>multiply.outer</code></a> with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html" rel="nofollow noreferrer"><code>numpy.ravel</code></a>:</p> <pre><code>a = pd.Serie...
python|pandas
3
12,220
50,107,824
How to replace string in sentence by index position
<p>How can I move a matching substring in a given sentence to the start of the sentence?</p> <p><code>col1</code> is always lowercase.</p> <p>I have:</p> <pre><code>col1 col2 output mmm2 Hello I want Mmm2 replace it Mmm2 Hello I want replace it mmm5 I want MMM5 replace it ...
<p>One method:</p> <pre><code>start_index = string.lower().index(target) new_string = target+string[0:start_index]+string[start_index+len(target):] </code></pre> <p>This will throw an error if <code>target</code> is not in <code>string</code>, and will only move the first instance if there are multiple.</p>
python|string|python-3.x|pandas
0
12,221
63,930,957
Drop rows containing a certain numeric pattern (int64) in pandas
<p>Surprisingly cannot find a simple answer.</p> <p>I have two columns in a dataframe. Column1 is <code>int64</code>.</p> <pre><code>Column1 Column2 19970101 400 19970102 300 19980101 200 </code></pre> <p>How to delete rows with <code>1997</code> pattern in <code>Column1</code>? It is not a string, so regular expr...
<p>Well:</p> <pre><code>df[df['Column1']//10000 != 1997] </code></pre> <p>Or converting it to string:</p> <pre><code>df[df['Column1'].astype(str).str[:4] != '1997'] </code></pre>
python|pandas|numeric
3
12,222
64,145,109
Pandas Udf in Pyspark running in only 1 Executor in yarn client or cluster mode
<p>I have a code which reads data from Hive Table and applies a pandas udf, the moment it reads data from table it runs in 11 executors , however the moment it executes a pandas udf it uses only 1 executor. Is there a way to assign say 10 executors to execute pandas udf</p> <pre><code>spark-submit --master yarn --deplo...
<p>may need to extract your UDF function to another file, then can broadcast to all executors.</p>
python|pandas|apache-spark|pyspark
0
12,223
63,889,408
pandas group by non zero average percentage across country
<p>I have a data frame like below.</p> <pre><code>import pandas as pd import numpy as np raw_data = {'Country':['UK','UK','UK','UK','UK','UK','UK','UK','UK','UK','UK','UK','UK','India','India','India','India','India','India','India','India','India','India','India','India','India'], 'Product':['A','A','A','A','C','...
<p>Let's try converting your logic to code:</p> <pre><code># count the non-zero value per country/product prods = df2['val'].ne(0).groupby([df2['Country'],df2['Product']]).sum() # count the number of products per country ids = df2.groupby('Country')['ID'].nunique() out = prods.div(ids).unstack().assign(Average=lambda...
python-3.x|pandas|pandas-groupby
2
12,224
63,988,444
Create a column based on value of another column using Pandas
<p>Please consider this data frame:</p> <pre><code>date value ------------------- 20201001 -100 20200202 200 20200303 0 ... </code></pre> <p>I want to hav1e another very simple column: &quot;Status&quot;</p> <p><strong>if Value &lt; 0 Then &quot;Status&quot; = -1</strong></p> <p><strong>if...
<p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.sign.html" rel="nofollow noreferrer"><code>numpy.sign</code></a>:</p> <pre><code>data['Status'] = np.sign(data['Value']) </code></pre> <p>If only integers use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.clip.html...
python|python-3.x|pandas
3
12,225
63,884,507
Pandas - ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(),
<p>I am trying to do a simple apply function over a data frame as follows:</p> <pre><code>titanic = pd.read_csv(&quot;/home/myuser/Downloads/titanic_train.csv&quot;) X_train = titanic.drop([&quot;Survived&quot;, &quot;PassengerId&quot;], axis=1) Y_train = titanic[&quot;Survived&quot;] X_test = titanic_test.drop([&quot...
<p>Instead of going through <code>df.iterrows()</code> try:</p> <pre><code>distances = X_train.apply(lambda f: calc_dist(f['test_row']), axis=1) </code></pre> <p>In this way you'll be creating a new column with the return value of the function <code>&quot;calc_dist&quot;</code> using as arg the column <code>'test_row'<...
python|pandas|algorithm|dataframe
1
12,226
63,885,032
How can I combine two Data Frames in Pandas Python?
<p>I have two DataFrames like below:</p> <pre><code>most_common_OMT = data[&quot;Order Method Type&quot;].value_counts().sort_values(ascending=False).to_frame() most_common_OMT </code></pre> <p><a href="https://i.stack.imgur.com/MXJWA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MXJWA.png" alt="en...
<p>Let us just do</p> <pre><code>out = pd.concat([most_common_OMT, profitability_OMT], axis=1) </code></pre>
python|pandas
1
12,227
63,989,934
How to extract rows from numpy array where value in col1 = a
<p>I have a 2d array of temperature values per year, where there are a few values given for each year. So the array looks something like this:</p> <pre><code>[[1960, a, b, c, d, e, f ...], [1960, a1, b1, c1, d1, e1, f1 ...], [1960, a2, b2, c2, d2, e2, f2 ...], [1961, a, b, c, d, e, f ...], [1961, a1, b1, c1, d1, e1...
<p>Let L be the your array. Then use the following code.</p> <pre><code>L[L[:, 1] == 1960][:, 0] </code></pre>
python|numpy|numpy-ndarray|data-processing|numpy-slicing
0
12,228
63,879,260
calculating the average of intervals given in a column entry in pandas
<p>I have a column in which I have depth intervals in some cells:</p> <p>The column looks like this</p> <pre><code> depth 0 0 1 1 2 2 3 0_1 4 1_2 </code></pre> <p>I want to know if there is a code I can use to find the average of the cells that are intervals in Pandas. The dataframe is very big and it woul...
<h3>Method 1:</h3> <p>Split the <code>depth</code> column using <code>Series.str.split</code> and create a new dataframe from this splitted column with <code>dtype=float</code> and take <code>mean</code> along <code>axis=1</code>:</p> <pre><code>df['depth'] = pd.DataFrame([*df['depth'].str.split('_')], dtype='float').m...
python|pandas|dataframe
1
12,229
46,902,138
Making batch tensorflow
<p>So I have this problem of making batch in my code, the thing is, I tried to search how we do batching but all I found was using some method like next_batch in MNIST sample program. I would really appreciate if someone could actually give me some tips on how I should make batch in my program below.</p> <pre><code>im...
<p>Keep extracting the batches of your data and keep feeding them to the network for training. In each epoch, all the samples of your training dataset should be run once. So you can rewrite your code like this:</p> <p>Required part of code only:</p> <pre><code>epochs = 4000 batch_size = 100 for epoch_no in range(epoc...
python|tensorflow|batch-processing
1
12,230
46,634,552
How to get value of a tensor from a Tensorflow Mode
<p>I am using the following implementation of the <code>Seq2Seq</code> model. Now, if I want to pass some inputs and get the corresponding values of encoder's hidden state (self.encoder_last_state), how can I do it?</p> <p><a href="https://github.com/JayParks/tf-seq2seq/blob/master/seq2seq_model.py" rel="nofollow nore...
<p>You need to first assemble <code>input_feed</code>, similar to the predict routine. Once you have that, just execute sess.run over the required hidden layer.</p> <p>To assmeble the input_feed:</p> <pre><code>input_feed = self.check_feeds(encoder_inputs, encoder_inputs_length, decoder_inputs=None, decoder_inputs_le...
tensorflow|deep-learning
1
12,231
63,086,879
combine arrays if duplicate element is found in another array python
<p>I have a list of arrays that go like:</p> <pre><code>[array(['A2', 'A1'], dtype=object), array(['A2', 'A3'], dtype=object), array(['A2', 'A4'], dtype=object), array(['A1', 'A3'], dtype=object), array(['A1', 'A4'], dtype=object), array(['A3', 'A4'], dtype=object), array(['B2', 'B1'], dtype=object), array(['B2'...
<p>It sounds like you want the connected components of a graph.</p> <pre><code>from numpy import array edges = [ array(['A2', 'A1'], dtype=object), array(['A2', 'A3'], dtype=object), array(['A2', 'A4'], dtype=object), array(['A1', 'A3'], dtype=object), array(['A1', 'A4'], dtype=object), array([...
python|arrays|numpy
1
12,232
62,914,666
Why does reshaping my data completely change the behaviour of a fully connected neural network in Keras?
<p>I would love some insight on this. I'm working on a regression problem in Keras with a simple neural network. I have train and test data, training data consists of 33230 samples with 20020 features (which is a ton of features for this amount of data, but that's another story - the features are just various measureme...
<p>A very good question. First of all you will have to understand how the network actually work. <code>Dense</code> layer is a fully conected layer so each neuron will have a connection with the previous layer's neuron. Now your networks Performance that you have mentioned that it is <code>1000x</code> time slower is n...
python|tensorflow|keras|neural-network
0
12,233
67,680,507
Converting string to date in the most concise way in a Pandas DataFrame
<p>I loaded a <code>DataFrame</code> from a csv file and one column contains a date/time string, in order to convert it to an actual date object I am currently doing this:</p> <pre class="lang-py prettyprint-override"><code>mydata[&quot;date_time&quot;] = pd.to_datetime(mydata[&quot;date_time&quot;], errors='raise') </...
<p>I will convert to date time with <code>read_csv</code></p> <pre><code>df = pd.read_csv('yourfile.csv', parse_dates=['date_time']) </code></pre>
python|pandas|dataframe
2
12,234
67,981,550
How to filter and find out all the columns of a certain data type in pandas dataframe?
<p>Let I've a dataframe <strong>df</strong></p> <pre><code> Name Age Job Rick 24 Worker Max 20 Worker Sam 48 Driver Expected output: Name Job </code></pre> <p>Now, I want to print out those column(name) which has <strong>object</strong...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.select_dtypes.html" rel="nofollow noreferrer"><code>df.select_dtypes</code></a> as follows:</p> <pre><code>df.select_dtypes('object').columns.to_list() </code></pre> <p>Output:</p> <pre><code>['Name', 'Job'] </code></pre...
python|pandas
4
12,235
68,011,416
How can I add results of a for loop with an if statement to my dataframe?
<p>I am new to python and I am having trouble with my loop/appending my results back to my original dataframe. Basically, I have a csv I am reading into python that has times of fish detection. I want to be able to classify the fish detection as either Day or Night. I am using the package Astral with an if statement, t...
<p>You don't need to use a <code>for</code> loop. Try using <code>apply()</code>.</p> <p><strong>Method1:</strong></p> <pre><code># Create sample data df = pd.DataFrame([pd.Timestamp('2014-01-23 00:00:00', tz='UTC'), pd.Timestamp('2014-01-23 12:00:00', tz='UTC')], columns=['DetectTime']) df.DetectTime = df.DetectTime.d...
python|pandas|dataframe|for-loop|append
0
12,236
67,664,938
Is it possible to create a for loop for a pandas df with 2 variables?
<p>I have a pandas dataframe that contains weight (weight column) information based on different users (user_Id column) and dates (date column/pandas data object).</p> <p>I would like to calculate the weight difference between the earliest and latest measurement for all users.</p> <p>To calculate the earliest and lates...
<p>Get min/max dates per user with groupby</p> <pre><code>min_dates = weight_info.groupby('Id').agg({'min':'date'}) max_dates = weight_info.groupby('Id').agg({'max':'date'}) </code></pre> <p>Then join with the weights to get the weight for the min/max date per user</p> <pre><code>min_weights = weight_info.merge( min_da...
python|pandas|for-loop|variables
1
12,237
61,420,874
category to binary response variable
<p>I am trying to convert my category to binary response variable.</p> <pre><code>y.sample(5) </code></pre> <p>Output:</p> <pre><code>7325944 Not Liable 6817854 Liable 7401930 Liable 1324151 Not Liable 3747135 Liable Name: hearing_disposition, dtype: object </code></pre> <pre><code>def co...
<pre><code>def convert_to_binary(x): if x=='Liable': return 0 if x=='Not Liable': return 1 y=y.transform(lambda value: convert_to_binary(value)) </code></pre> <p>Explanation: transform() can also be used without giving any keys (like you have mentioned while applying apply()) as 'y' is a Series. Thi...
python|python-3.x|pandas
0
12,238
61,256,979
random.seed() does not work with random.choice()
<p>So i'm trying to generate a list of numbers with desired probability; the problem is that <code>random.seed()</code> does not work in this case. </p> <pre><code>M_NumDependent = [] for i in range(61729): random.seed(2020) n = np.random.choice(np.arange(0, 4), p=[0.44, 0.21, 0.23, 0.12]) M_NumDependent....
<p><code>numpy</code> uses its own pseudo random generator. You can seed the Numpy random generator with <a href="https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.random.seed.html#numpy.random.seed" rel="noreferrer"><strong><code>np.random.seed(..)</code></strong> [numpy-doc]</a>:</p> <pre><code><b>np...
python|numpy|random
5
12,239
68,698,870
Python pandas group by and eliminate
<div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">a</th> <th style="text-align: center;">b</th> <th style="text-align: right;">c</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">es</td> <td style="text-align: center;">ss</td> <td style="text-align: right;">...
<p>I hope I've understood your question right:</p> <pre class="lang-py prettyprint-override"><code>x = ( df.sort_values(by=[&quot;a&quot;]) .drop_duplicates(&quot;b&quot;, keep=&quot;first&quot;) .sum(axis=1) .to_frame(&quot;cleaned&quot;) ) print(x) </code></pre> <p>Prints:</p> <pre class="lang-none p...
python|python-3.x|pandas|dataframe|pandas-groupby
1
12,240
68,555,557
pandas: fill empty column with alternate values
<p>I have a dataframe as follows, but with more rows</p> <pre><code>import pandas as pd import numpy as np d = {'col1': ['data1', 'data2','data3','data4','data5'], 'col2': ['a', 'b','c','d','e']} df = pd.DataFrame(data=d) </code></pre> <p>I have added an empty column to this dataframe</p> <pre><code>df['type...
<p>try:</p> <pre><code>df['type']=np.where(df.index%2==0, 'type_a', 'type_b') </code></pre> <p>output of df:</p> <pre><code> col1 col2 type 0 data1 a type_a 1 data2 b type_b 2 data3 c type_a 3 data4 d type_b 4 data5 e type_a </code></pre>
python|pandas|numpy|alternate
1
12,241
68,805,869
Iterate through excel files' sheets and append if sheet names share common part in Python
<p>Let's say we have many excel files with the multiple sheets as follows:</p> <p>Sheet 1: <code>2021_q1_bj</code></p> <pre><code> a b c d 0 1 2 23 2 1 2 3 45 5 </code></pre> <p>Sheet 2: <code>2021_q2_bj</code></p> <pre><code> a b c d 0 1 2 23 6 1 2 3 45 7 </code></pre> <p>Sheet 3: <code>201...
<p>Try:</p> <pre><code>dfs = pd.read_excel('Downloads/WS_1.xlsx', sheet_name=None, index_col=[0]) df_out = pd.concat(dfs.values(), keys=dfs.keys()) for n, g in df_out.groupby(df_out.index.to_series().str[0].str.rsplit('_', n=1).str[-1]): g.droplevel(level=0).dropna(how='all', axis=1).reset_index(drop=True).to_exc...
python-3.x|pandas|dataframe|openxlsx
1
12,242
68,791,877
Trying to create optimizer slot variable under the scope for tf.distribute.Strategy which is different from the scope used for the original variable
<p>I'm trying to train, save and load a tensorflow model. An outline of my code is as follows:</p> <pre><code>devices = [&quot;/device:GPU:{}&quot;.format(i) for i in range(num_gpus)] strategy = tf.distribute.MirroredStrategy(devices) with strategy.scope(): # Create model model = my_model(some parameters) m...
<p>According to <a href="https://www.tensorflow.org/api_docs/python/tf/distribute/Strategy" rel="nofollow noreferrer">this</a> model-saving APIs create variables (which should be distributed variables). Try creating/calling the callbacks from within the strategy scope.</p>
tensorflow|tensorflow2.0
0
12,243
53,041,396
implementing image classification in rnn
<p>I have implemented an example of classifying cats and dogs using cnn. You can get the code from <a href="https://github.com/venkateshtata/cnn_medium./tree/master" rel="nofollow noreferrer">here</a> and <a href="https://becominghuman.ai/building-an-image-classifier-using-deep-learning-in-python-totally-from-a-beginne...
<p>Keras provides an example of how to classify the <a href="https://en.wikipedia.org/wiki/MNIST_database" rel="nofollow noreferrer">MNIST</a> dataset using an <a href="https://en.wikipedia.org/wiki/Long_short-term_memory" rel="nofollow noreferrer">LSTM</a> <a href="https://github.com/keras-team/keras/blob/master/examp...
python|tensorflow|keras
3
12,244
65,599,297
Differencies between OneHotEncoding (sklearn) and get_dummies (pandas)
<p>I am wondering what is the difference between pandas' <code>get_dummies()</code> encoding of categorical features as compared to the sklearn's <code>OneHotEncoder()</code>.</p> <p>I've seen answers that mention that <code>get_dummies()</code> cannot produce encoding for categories not seen in the training dataset (<...
<p>If you apply <code>get_dummies()</code> and <code>OneHotEncoder()</code> in the general dataset, you should obtain the same result.</p> <p>If you apply <code>get_dummies()</code> in the general dataset, and <code>OneHotEncoder()</code> in the train dataset, you will probably obtain a few (very small) differences if ...
python|training-data|sklearn-pandas|one-hot-encoding
0
12,245
65,716,925
Tensorflow dataset from numpy array
<p>I have two numpy Arrays (X, Y) which I want to convert to a tensorflow dataset. <a href="https://www.tensorflow.org/tutorials/load_data/numpy#load_numpy_arrays_with_tfdatadataset" rel="nofollow noreferrer">According to the documentation</a> it should be possible to run</p> <pre><code>train_dataset = tf.data.Dataset....
<p>It will work if you batch your dataset:</p> <pre><code>train_dataset = tf.data.Dataset.from_tensor_slices((a,b)).batch(4) </code></pre>
python|numpy|tensorflow|keras
1
12,246
63,505,160
Pandas Combine Same value rows and split different value columns
<p>Suppose I have following dataframe:</p> <pre><code>ID Year Month count 1 2017 8 20 2 2018 8 16 3 2017 8 4 1 2018 8 109 3 2018 8 4 </code></pre> <p>I am trying to get output in following format:</p> <pre><code>ID Year_2017 Year_2018 Month 1 ...
<p>The point is to divide it up by the terms of the year and combine it with the ID. The rest is column names and removing unnecessary columns.</p> <pre><code>df2017 = df[df['Year'] == 2017] df2018 = df[df['Year'] == 2018] new = df2018.merge(df2017, on='ID', how='outer') new.columns = ['ID', 'tmp_x', 'Month', 'Year_201...
python|pandas
1
12,247
53,734,364
Performing Perspective transform when not all corners are visible python openCV
<p>Im trying to do perspective transform on a video of a football pitch, I have found many resources for ways of doing this when all four corners of the pitch are visible however how can i do this when not all corners are visible? maybe a way of extrapolating beyond the video box? </p>
<p>Instead of using the four corners of the field, use the part of the field that is visible. In this image, the field is visible only to the 50 yard line. </p> <p><a href="https://i.stack.imgur.com/YF2FI.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YF2FI.jpg" alt="football field"></a></p> <p>Tw...
python|opencv|tensorflow|computer-vision
1
12,248
56,740,492
shuffle Custom Image Data Generator on_epoch_end
<p>I am trying to write custom image data generator custom class is inherited from keras.utils.Sequence but i get error on "on_epoch_end", says not enough values to unpack</p> <pre class="lang-python prettyprint-override"><code>class CityscapesGenerator(Sequence): def __init__(self, folder='/cityscapes_reordered',...
<p>I would recommend checking <a href="https://stackoverflow.com/questions/19339/transpose-unzip-function-inverse-of-zip/22115957">Transpose/Unzip Function (inverse of zip)?</a>. This explains several scenarios where zip(*arg) doesn't yield the expected results.</p> <p>It is possible that the first call to <code>on_ep...
python-3.x|tensorflow|keras|generator
0
12,249
67,047,239
Rearrange pandas personality dataframe
<p>I have the following dataframe in my code:</p> <pre><code>uid A O N C E 8e7cebf9a234c064b75016249f2ac65e 5 2 3 3 6 77c7d756a093150d4377720abeaeef76 1 2 1 3 4 b7e8a92987a530cc368719a0e60e26a3 6 4 4 1 3 ... ...
<p>You just need <a href="https://pandas.pydata.org/docs/reference/api/pandas.melt.html" rel="nofollow noreferrer"><code>melt()</code></a> method:</p> <pre><code>result=df.melt(id_vars='uid',var_name='trait',value_name='rating') </code></pre> <p>Now if you print <code>result</code> you will get your desired output</p>
python|pandas
1
12,250
47,234,513
numpy getting the not min or max element out of three elements
<p>I have a three dimensional array :</p> <pre><code> y = np.random.randint(1,5 ,(50,50,3)) </code></pre> <p>I want to compute the max and min across the third axis (3 elements), and then divide by the remaining number/element.</p> <p>So something like this:</p> <pre><code>x = (np.max(y, axis =2) - 2*np.min(y, axis...
<p>Another alternative is to use <code>np.median</code> </p> <pre><code>(y.max(2) - 2 * y.min(2)) / np.median(y, 2) </code></pre>
python|numpy
5
12,251
68,276,010
ValueError: Must have equal len keys and value when setting with an iterable when inserting a list
<p>Here's the scenario I met. I have a json like dictionary and intend to count the number of answers from another dataframe with the same column name (Question number I would say)</p> <pre class="lang-py prettyprint-override"><code>aa = { &quot;Q1&quot;: { &quot;Number&quot;: 100, &quot;Question&qu...
<p>You could try this:</p> <pre class="lang-py prettyprint-override"><code># New column df[&quot;Answer Count&quot;] = pd.NA # Iterate on each grade in df and count values in table for question_number, row in df.iterrows(): if question_number in table.columns: answer_count = [] for answer in row[&q...
python|pandas|dataframe
1
12,252
68,048,465
i try to deploy my machine learning model using flask and get error SystemExit: 1
<p>error :</p> <pre><code>runfile('C:/Users/Ahmed Sabry Tamam/.spyder-py3/temp.py', wdir='C:/Users/Ahmed Sabry Tamam/.spyder-py3') * Serving Flask app &quot;temp&quot; (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI ...
<p>I also got the same error.</p> <p>But I tried using the debug mode is off</p> <pre><code>if __name__ == '__main__': app.run(debug=False) </code></pre> <p>I didn't got any error.</p>
python|tensorflow|flask|keras
0
12,253
59,145,651
Pandas: Adding new rows depending on a group aggregation
<p>Please help!</p> <p>There are a total of 5 Rejection Codes: EL1, EL2, EL3, EL4, and EL5. I want to append new rows so that each ID has 5 reject codes always. </p> <p>Here's my original DF:</p> <pre><code>+----+-------------+-----+ | ID | Reject Code | QTY | +----+-------------+-----+ | A | EL1 | 7 | | ...
<p>You can do <code>pivot_table</code>, then <code>melt</code>/<code>stack</code>:</p> <pre><code># all reject codes Rej_Codes = [f'EL{i+1}' for i in range(5)] (df.pivot_table(index='ID', columns='Reject Code', values='QTY', fill_value=0) .reindex(Rej_Codes, axis=1, ...
python|pandas
5
12,254
59,316,974
How to find next value in dataframe compare with last value in database?
<p>I have dataframe like this.</p> <pre><code>print(df['Test_Id']) 0 1 1 2 2 3 3 5 4 6 5 8 6 9 </code></pre> <p>And I can find last value of MySQL like this</p> <pre><code>def get_last_id_db(): last_id = 0 mycursor = mydb.cursor(buffered=True) sql = "SELECT * FROM lo...
<p>Assuming that your index has no skips:</p> <pre class="lang-py prettyprint-override"><code>last_id = get_last_id_db() last_idx = df.loc[df['Test_Id'] == last_id, 'Test_Id'].index[0] next_id = df.iloc[last_idx + 1] </code></pre>
python|python-3.x|pandas|dataframe
0
12,255
59,320,268
Able to extract proper dtypes of a DF in Local but if i tried the same in GCP Dataproc (Source input file) facing the issue
<p>Am able to extract the datatypes of the DF (DF created from a CSV file).</p> <p>When i tried the same in dataproc getting all datatypes as "string". can i get any help here:</p> <p>Code which worked in Local Machine for me.</p> <pre><code>df = spark.read.option("header","true").option("inferSchema","true").csv("...
<p>I've been trying to reproduce your issue, and the problem might be residing within the CSV format. </p> <p>I tried to reproduce the issue with the next CSV sample that I could found with different types called <a href="https://support.spatialkey.com/spatialkey-sample-csv-data/" rel="nofollow noreferrer">Sample insu...
python|pandas|google-cloud-platform|google-cloud-storage|pyspark-dataframes
0
12,256
66,496,086
TypeError: fit_generator() missing 1 required positional argument: 'generator'
<p>I am trying to train a CNN to detect if an image is deepfake or not , but upon running the code I keep getting this error: TypeError: fit_generator() missing 1 required positional argument: 'generator' How do I get rid of this error? Is there an issue with my code? Im also not sure if the classifier class is necessa...
<p>3 or 4 Mistakes i can see :</p> <p>For subclassing in keras:</p> <ul> <li>You need to call <code>super(YourClass, self).__init__()</code></li> <li>You define your model inside a <code>call</code> method</li> </ul> <p>Check this <a href="https://www.tensorflow.org/guide/keras/custom_layers_and_models" rel="nofollow n...
python|tensorflow|keras|conv-neural-network
1
12,257
66,643,771
DataFrame of Dates into sequential dates
<p>I would like to turn a dataframe as follows into a data frame of sequential dates.</p> <pre><code>Date 01/25/1995 01/20/1995 01/20/1995 01/23/1995 </code></pre> <p>into</p> <pre><code>Date Value Cumsum 01/20/1995 2 2 01/21/1995 0 2 01/22/1995 0 2 01/23/1995 1 3 0...
<p>Try this:</p> <pre><code>df['Date'] = pd.to_datetime(df['Date']) df_out = df.assign(Value=1).set_index('Date').resample('D').asfreq().fillna(0) df_out = df_out.assign(Cumsum=df_out['Value'].cumsum()) print(df_out) </code></pre> <p>Output:</p> <pre><code> Value Cumsum Date 1995-01-20 ...
python-3.x|pandas
4
12,258
66,428,037
Not able to groupby apply function with two arguments in Python
<p>My question is related to <a href="https://stackoverflow.com/questions/43615962/pandas-groupby-apply-a-function-with-two-arguments">this one</a>. I have a Pandas DataFrame as shown below. I want to calculate MAPE after grouping by <code>period</code>. However, I'm getting an error when trying to do so. What am I doi...
<p>Change the function to:</p> <pre><code>def mape(data, act, fct): act = data[act] fct = data[fct] return np.sum(abs((act - fct)/act))/len(act) </code></pre> <p>While using <code>groupby.apply</code>, the data of the group is passed to the function as first argument.</p>
python|pandas|function
4
12,259
57,627,804
Using Numpy to multiply table row data
<p>I am trying to learn numpy for an imoplementation I have been working on.</p> <p>I need to build a table. and multiply certain number of rows based on another set of rows. And then write the rows to a csv.</p> <p>In Python I am doing something like this</p> <pre><code>def test_write(): initial_rows_data_list ...
<p>You don't need pandas to write to a CSV file. You can use the csv module. </p> <pre><code>import csv // def test_write if __name__ == "__main__": with open('test.csv', 'w') as csvfile: csvwriter = csv.writer(csvfile) for row in test_write(): csvwriter.writerow(row) </code></pre> ...
python|numpy
1
12,260
73,089,611
change cell value based on condition
<pre><code>username status debt John pending $1000 Mike pending $0 Daymond cleared $0 </code></pre> <p>How can I change the status of pending to cleared if the status is pending and debt is 0?</p>
<p>You can use</p> <pre class="lang-py prettyprint-override"><code>m = df['status'].eq('pending') &amp; df['debt'].eq('$0') df.loc[m, 'status'] = 'cleared' # or df['status'] = df['status'].mask(m, 'cleared') # or df['status'] = np.where(m, 'cleared', df['status']) </code></pre> <pre><code>print(df) username statu...
python|pandas|dataframe
0
12,261
70,735,851
PyTorch cudnn_cnn_train64_8.dll existed but could not be found when using spacy to download
<p>When I used spacy (a library) to download, it showed that</p> <p><code>OSError: [WinError 127] The specified procedure could not be found. Error loading &quot;C:\Users\haoli\anaconda3\envs\ifcmapping\lib\site-packages\torch\lib\cudnn_cnn_train64_8.dll&quot; or one of its dependencies.</code></p> <p>But <code>cudnn_c...
<p>It seems that it is because I used <code>conda</code> to install PyTorch and used <code>pip</code> to install the spacy library. When I used <code>conda</code> to install both of them it worked.</p>
pytorch|spacy|cudnn|oserror
0
12,262
51,271,775
pandas + bokeh - How get dataframe column name for hover tool
<p>I plot lines from some columns of a dataframe. I would like the hover tool to display the name of the column that originated that data and also some information from other columns not plotted.</p> <p>For example, in the code below I would like the hover tool to display "Name = A; Aux = 0.1" when the mouse is over t...
<p>There is a recent feature to support this. With Bokeh <code>0.13.0</code> or newer, you can set the <code>name</code> on a glyph and refer to that name in a tooltip with <code>$name</code>. Additionally, you can refer to a <em>column</em> with that name with <code>@$name</code>. However, the "indirection" column has...
python|python-3.x|pandas|bokeh
10
12,263
51,196,382
Python pandas groupby category and integer variables results in pandas last and tail difference
<p><strong>UPDATE: Please download my full dataset <a href="https://www.dropbox.com/s/46z49g93tvrkrwv/sf.csv?dl=0" rel="nofollow noreferrer">here</a>.</strong></p> <p>my datatype is:</p> <pre><code>&gt;&gt;&gt; df.dtypes increment int64 spread float64 SYM_ROOT category dtype: object </code></pre> <p...
<p>It is actually an issue here at <a href="https://github.com/pandas-dev/pandas/issues/17594" rel="nofollow noreferrer">Github</a>, where the problem is mainly caused by groupby categories guessing the values. </p>
python|pandas|time-series
0
12,264
70,971,041
Is it possible to add tensors of different sizes together in pytorch?
<p>I have an image gradient of size <code>(3, 224, 224)</code> and a patch of <code>(1, 768)</code>. is it possible to add this gradient to the patch to get a size of the patch <code>(1, 768)</code>?</p> <p>Forgive my inquisitiveness. I know pytorch too utilizes broadcasting and I am not sure if I will able to do so wi...
<p>No. Whether two tensors are broadcastable is defined by the following <a href="https://pytorch.org/docs/stable/notes/broadcasting.html#general-semantics" rel="nofollow noreferrer">rules</a>:</p> <ul> <li><p>Each tensor has at least one dimension.</p> </li> <li><p>When iterating over the dimension sizes, starting at ...
pytorch
2
12,265
51,848,413
How to set a row index in python when the column index changes?
<p>I am trying to read in a csv of company financial information. The row index name is always changing though depending on the company (for instance with facebook the row index name is "Fiscal year ends in December. USD in millions except per share data." but for another company it will say fiscal year ends January......
<p>Use csv.DictReader and set the fieldnames (or headers)</p>
python|pandas
0
12,266
35,937,456
Does BallTree support customized metric with irregular data now?
<p>I have a dataset describing some traces in following form:</p> <pre><code>traceId1: event1 time1 event2 time2 ... eventN timeN traceId2: event1 time1 event2 time2 ... eventM-1 timeM-1 eventM timeM . . . </code></pre> <p>Namely, this file contains several traces. Each trace consists of several events and the time a...
<p>The Ball Tree will only work with data that can be formed into a 2D floating point array. You can see this in the initialization of the object <a href="https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/neighbors/binary_tree.pxi#L1053" rel="nofollow">in the source code</a>. I do not anticipate that the...
numpy|machine-learning|scikit-learn
1
12,267
37,479,532
Pandas apply a change which affects 2 columns at the same time
<p>I have the dataframe below. bet_pl and co_pl keep track of the daily changes in the 2 balances. I have updated co_balance based on co_pl and the cumsum.</p> <pre><code>init_balance = D('100.0') co_thresh = D('1.05') * init_balance def get_pl_co(row): if row['eod_bet_balance'] &gt; co_thresh: diff = row...
<p>First, you don't need to apply a custom function to get <code>co_pl</code>, it could be done like so:</p> <pre class="lang-py prettyprint-override"><code>df['co_pl'] = (df['eod_bet_balance'] - co_thresh).clip_lower(0) </code></pre> <p>As for updating the other column, if I understand correctly you want something l...
python|pandas
1
12,268
37,164,718
Pandas: replace values of a series by lookup of index
<p>I want to replace some values in a series using a lookup table for certain indices. For example:</p> <pre><code>s1 = Series.(['keep', 'replace', 'replace'}, index=['p1', 'p2', 'p3']) lookup = {'p2' : 'altered', 'p3' : 'changed'} # desired series s1: # p1 keep # p2 altered # p3 changed </code></pre> <p>Sure,...
<p>Using your initial (simple) example, you can do:</p> <pre><code>In [29]: s1.update(pd.Series(lookup)) In [30]: s1 Out[30]: p1 keep p2 altered p3 changed dtype: object </code></pre>
python|dictionary|pandas|replace|series
1
12,269
42,116,957
regarding reshaping a multi-dimensional array
<p>I have a multidimensional array with shape <code>(15000,1,96,96),</code> where each 96*96 matrix represents an image. I would like to transform its shape to <code>(15000,96,96,1).</code></p> <p>Can I just use <code>a=a.reshape(15000,96,96,1)</code> to do it? Is that the right way?</p>
<p>For your specific example you need to transpose the 2nd dimension with the final one. You can shuffle dimensions in a numpy array using the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html" rel="nofollow noreferrer">transpose method</a>:</p> <p>For example:</p> <pre><code>a = np.z...
python|numpy|scipy
1
12,270
41,744,275
Which method does pandas use for percentile?
<p>I was trying to understand lower/upper percentiles calculation in pandas and got a bit confused. Here is the sample code and output for it.</p> <pre><code>test = pd.Series([7, 15, 36, 39, 40, 41]) test.describe() </code></pre> <p>output: </p> <p><a href="https://i.stack.imgur.com/NamY6.png" rel="nofollow noreferr...
<p>As I mentioned in the comments, I finally figured out how it works by trying <code>from pandas.core.algorithms import quantile</code> using <code>quantile</code> function as @Abdou suggested.</p> <p>I am not that good to explain it only by typing, therefore I will do it only on the given example for 25% and 75% for...
pandas|percentile|quartile
6
12,271
37,813,244
Appending a dataframe Pandas
<p>Can't seem to do this at all.</p> <p>So I have </p> <pre><code>df.Name.unique() </code></pre> <p>Which spits out a list of names. </p> <pre><code>['BKH' 'EDE'] </code></pre> <p>And I have </p> <pre><code>new = pd.DataFrame(columns=['Name']) </code></pre> <p>And I want to append new to essentially have a list ...
<p>actually guys its all good I have figure it out </p> <pre><code>values = df.Name.unique() new['Name'] = values print(new) </code></pre> <p>spits out </p> <pre><code> Name 0 BKH 1 EDE </code></pre>
pandas|dataframe|append|np
0
12,272
37,978,336
Parallelizing 3D numpy array calculation using dask.array.core.map_blocks
<p>I have a 3D numpy array (dimensions: depth, latitude, longtitude) and I am trying to do some parallelized calculation using the data along the depth axis at each lat-lon point and so far I have been unsuccessful. I've looked at the documentation for <code>dask.array.core.map_blocks</code> but it has not been helpful...
<p>Chunks should either be a tuple of integers specifying a uniform chunkshape across the full array</p> <pre><code>chunks=(49, 32, 12) </code></pre> <p>Or it should be a tuple of tuples, each tuple defining how to chunk up each dimension.</p> <pre><code>chunks=((20, 20, 9), (8, 8, 8, 8), (12, 24, 24, 12)) </code></...
python|numpy|parallel-processing|dask
0
12,273
64,560,216
Convert .txt file to .csv with specific columns PYTHON
<p>I have some text file that I want to load into my python code, but the format of the txt file is not suitable.</p> <p>Here is what it contains:</p> <pre><code>SEQ MSSSSWLLLSLVAVTAAQSTIEEQAKTFLDKFNHEAEDLFYQSSLASWNY SS3 CCCHHHHHHHHHHHHCCCCCCHHHHHHHHHHHHHHHHHHHHHHHHHHHHH 95024445656543114678678999999999999999888...
<h2>Steps</h2> <ol> <li>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_fwf.html" rel="nofollow noreferrer">pd.read_fwf()</a> to read files in a fixed-width format.</li> <li>Fill the missing values with the last available value by <a href="https://pandas.pydata.org/pandas-docs/stable...
python|pandas|csv|txt
1
12,274
64,344,016
Perform linear regression with sunspot dataset
<p>I'm trying to perform a linear regression using k-fold validation, in the sunspost dataset. In this exercise I need to take the last 10 years as test and use the rest for tranning, further I should measure the model accuracy using RMSE. Also, I need to test k-values from 1 to 24 in order to identify the better k val...
<p>In fact, the problem was that I've had prepare the date before, using the shift function in order to fit the 24 delays that I wanted, before perform the k-fold.</p>
python|machine-learning|scikit-learn|linear-regression|sklearn-pandas
0
12,275
47,756,617
How to use fillna together with groupby for time series?
<p>I have the following dataset:</p> <pre><code>Date,Day,A,B,C 2015/03/23,Mo,60085,105744,18623 2015/03/24,Tu,41472,70327,14775 2015/03/25,We,46644,81693,17168 2015/03/26,Th,43640,74615,15577 2015/03/27,Fr,37503,67754,13278 2015/03/28,Sa,,, 2015/03/29,Su,,, 2015/03/30,Mo,61904,108128,19600 2015/03/31,...
<p>I am assuming that none of the dates are missing.</p> <pre><code>df['date'] = df['date].map(lambda x:datetime.strptime(x,"%d/%m/%Y")) df.sort_values(by=['date'],inplace=True) cols = ['v1','v2','v3','v4'] cols_last_week = [i+'_last_week' for i in cols] df[cols_last_week] = df[cols].shiftby(7) </code></pre> <p>Let's...
python|pandas|pandas-groupby
0
12,276
47,920,650
Better way to parse CSV into list or array
<p>Is there a better way to create a list or a numpy array from this <a href="https://drive.google.com/file/d/1BwmIoMM4eZGdedTaWrK6WSMhwdo4f1o3/view?usp=sharing" rel="nofollow noreferrer">csv file</a>? What I'm asking is how to do it and parse more gracefully than I did in the code below.</p> <pre><code>fname = open(...
<p>You can always use <a href="https://pandas.pydata.org" rel="nofollow noreferrer">Pandas</a>. As an example,</p> <pre><code>import pandas as pd import numpy as np df = pd.read_csv('pandas_dataframe_importing_csv/example.csv') </code></pre> <p>To convert it, you will have to convert it to your favorite numeric type...
python|python-3.x|csv|numpy
2
12,277
47,867,249
How to get percentage count based on multiple columns in pandas dataframe?
<p>I have 20 columns in a dataframe. I list 4 of them here as example:</p> <p>is_guarantee: 0 or 1<br> hotel_star: 0, 1, 2, 3, 4, 5<br> order_status: 40, 60, 80<br> journey (Label): 0, 1, 2 </p> <pre><code> is_guarantee hotel_star order_status journey 0 0 5 60 0 1 ...
<p>I think you need:</p> <ul> <li>reshape by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow noreferrer"><code>melt</code></a> and get counts by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>g...
python|pandas|numpy|matrix
1
12,278
70,278,857
Replace dataframe values via n lists
<p>Couldn't really find sth appropriate here in stackoverflow - I want to classify data in a dataframe column via <em>n</em> lists. An example for the df would be:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ID</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>19</td> <td>blue</...
<p>Building upon Pierre Massé answer: I agree that creating a mapping with a dict is and applying <code>.replace(mapping_dict)</code> is a nice way to go about it. I think the final solution can a a bit cleaner though.</p> <pre><code>colors = ['red', 'green', 'blue'] temperatures = ['hot', 'medium', 'cold'] # create a...
python|pandas
0
12,279
56,080,728
loops in python for different combinations
<p>I have seven dataframes tbl1851, tbl1861, tbl1871, tbl1881, tbl1891, tbl1901, tbl1911.</p> <p>Each dataframe has the same fields 'Sex', 'Age', 'Num'.</p> <p>I want to select a subset from each dataframe by first creating series of boolean.</p> <p>My code looks like</p> <pre><code>AM1851 = ((tbl1851.Sex=="M") &am...
<p>Instead of having each dataframe as a separate variable, put them in a list:</p> <pre><code>frames = [ # dataframe 1, # dataframe 2, # etc. ] </code></pre> <p>Then you can easily loop through them to create another list:</p> <pre><code>AMs = [] for frame in frames: AMs.append((frame.Sex=="M") &amp...
python|pandas|loops|dataframe
1
12,280
56,133,089
How to change yyyymmdd format to mm-dd-yyyy in pandas dataframe?
<p>I'm trying to reformat a xlsx file with column incident history (e.g. Class II : O : 20181119) yyyymmdd to mm-dd-yyyy in the dataframe but the caveat is that some cells are unequal with some with more than one Class</p> <p><a href="https://i.stack.imgur.com/Oprdt.jpg" rel="nofollow noreferrer"><img src="https://i.s...
<p>It looks like you're close. The following worked for me:</p> <pre><code>import pandas as pd data = ['Class II: R : 20180920','Class II: O : 20181119','Class II: D1: 20170601','Class O: D1: 20190219'] df = pd.DataFrame({"incident_history":data}) def extract_dt(dt_str): out_str = dt_str[dt_str.rfind(":")+1:].s...
python|pandas
0
12,281
56,005,506
How can I split strings in a column only when a certain word occurs?
<p>I would like to only retain the part after the word 'in' if it occurs in a row of a column. The problem is that if this word does not occur in the row, its original value is replaced by NaN. I would like to keep the original values if the word 'in' does not appear. </p> <p>I have tried splitting the string using st...
<p>One possible solution is replace missing values by original column:</p> <pre><code>df['new'] = df.city.astype(str).str.split(' in ').str[1].fillna(df.city) print (df) city new 0 Rotterdam Rotterdam 1 Den Haag ...
python|string|pandas|dataframe|split
2
12,282
55,976,652
X X^T Matrix is not positive definite, although it should be
<p>I have a matrix <code>M</code> where <code>M.shape = (679, 512)</code>. </p> <p>I would like to find the eigenvectors and eigenvalues of <code>M M^T</code>, it's covatiance matrix, which should be positive definite in maths. I find them using:</p> <pre><code>import numpy as np v, w = np.linalg.eig(np.matmul(M, M.T...
<p><em>"Shouldn't M M^T be positive semi definite, giving positive and real eigenvalues only?"</em> If you change "positive" to "nonnegative", then yes, that is true mathematically. In fact, instead of <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eig.html" rel="nofollow noreferrer"><code...
numpy|linear-algebra
1
12,283
64,999,667
Replace with first occurrence value for duplicate columns using pandas or python
<p>I have data like</p> <pre><code>ca ca ca 120.00 ca cc cd 130.00 ca ca ca 135.23 ca ha ca 60.00 ca ha ca 50.00 </code></pre> <p>If first 3 columns are equal then fourth column value should be the first occurrence. I want data like</p> <pre><code>ca ca ca 120.00 ca cc cd 130.00 ca ca ca 120.00 ca ha ca 60.00 c...
<p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html" rel="nofollow noreferrer"><code>GroupBy.transform</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.first.html" rel="nofollow noref...
python|pandas
2
12,284
64,796,049
How do I export multiple numpy arrays to a text file with a specific delimiter and line breaks?
<p>I have the following three numpy arrays in my python file:</p> <pre><code>array([[ 1, 1, 14, 1, 15], [ 2, 1, 14, 1, 13], [ 3, 1, 15, 1, 13]]) array([[ 1, 1, 1, 13], [ 2, 1, 1, 14], [ 3, 1, 1, 15]]) array([...
<p>As outlined in my comments:</p> <pre><code>In [48]: with open('test.txt','w') as f: ...: f.write('ListA\n\n') ...: np.savetxt(f, np.ones((3,4),int), fmt='%d') ...: f.write('\nListB\n\n') ...: np.savetxt(f, np.arange(12).reshape(3,4), fmt='%d') ...: f.write('\nListC\n\n') ....
python|arrays|numpy
1
12,285
40,247,095
R foverlaps equivalent in Python
<p>I am trying to rewrite some R code in Python and cannot get past one particular bit of code. I've found the <code>foverlaps</code> function in R to be very useful when performing a time-based join, but haven't found anything that works as well in Python3. </p> <p>What I am doing is joining two data tables where the...
<p>Consider a straightforward merge with subset using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.between.html" rel="nofollow"><code>pandas.Series.between()</code></a>. Merge joins all combinations of the join columns and the subset keeps rows that align to time intervals.</p> <pre><co...
python|r|pandas|join|bigdata
3
12,286
39,671,956
How to Increment a Variable in Tensorflow?
<p>When trying to use the supervisor in Tensorflow I was made aware that :</p> <blockquote> <p>your training op is responsible for incrementing the global step value.</p> </blockquote> <p>(<a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/how_tos/supervisor/index.md" rel="nofollow">Refe...
<p>Pretty simple solution:</p> <pre><code>global_step = tf.Variable(1, name='global_step', trainable=False, dtype=tf.int32) increment_global_step_op = tf.assign(global_step, global_step+1) </code></pre> <p>Then when you want to increment it, just run that op under the current <code>tf.Session</code> <code>sess</code>...
python-2.7|tensorflow
18
12,287
39,601,165
Python get a value from numpy.ndarray by [index]
<pre><code>import numpy as np ze=np.zeros(3) print(ze[0]) # -&gt; 0 </code></pre> <p>I am pretty new to Python (3.5.2)</p> <p>I learned 'list' in python and to show the i th element in list1</p> <pre><code>print (list1[i]) </code></pre> <p>but, even 'np.zeros(3)' is ndarray, a class in NumPy, it can be used as t...
<p>If you want to implement a class that can return a value using the [] operator. Then implement the <code>__getitem__(self, key)</code> function in the class, see <a href="https://docs.python.org/2/reference/datamodel.html#emulating-container-types" rel="nofollow">https://docs.python.org/2/reference/datamodel.html#em...
python|numpy
1
12,288
44,090,179
'numpy.ndarray' object has no attribute 'mode'
<p>I got an error with this code:</p> <pre><code>import PIL.ImageOps inverted_image = PIL.ImageOps.invert(image) </code></pre> <p>The traceback is</p> <pre><code>Traceback (most recent call last): File "filter.py", line 32, in &lt;module&gt; inverted_image = PIL.ImageOps.invert(denoise) File "/usr/lib/python...
<p>The Exception is raised if you try to do <a href="http://pillow.readthedocs.io/en/3.1.x/reference/ImageOps.html#PIL.ImageOps.invert" rel="nofollow noreferrer"><code>ImageOps.invert</code></a> on a <code>numpy.ndarray</code>:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; from PIL import Image &gt;&gt;&...
python|numpy|python-imaging-library
4
12,289
44,318,962
Creating new pandas dataframe after performing complex function
<p>I have trajectory data in following df:</p> <pre><code> vid points 0 0 [[2,4], [5,6], [8,9]] 1 1 [[10,11], [12,13], [14,15]] 2 2 [[1,2], [3,4], [8,1]] 3 3 [[21,10], [8,8], [4,3]] 4 4 [[15,2], [16,1], [17,3]] </code></pre> <p>each trajectory is a list points, id...
<p>Make a custom <code>class</code> where you define subtraction as <code>method_dist</code></p> <pre><code>def method_dist(x, y): return abs(x - y) class Trajectory(object): def __init__(self, a): self.data = np.asarray(a) def __sub__(self, other): return method_dist(self.data, other.dat...
python|pandas|numpy|dataframe
1
12,290
44,230,325
python, pandas: InvalidIndexError when creating dataframe
<p>I have been exploring the <a href="https://www.kaggle.com/c/titanic/data" rel="nofollow noreferrer">titanic dataset</a>. I am trying to create a <code>dataframe</code> which will have the ages of the people who survived the titanic sinking, and those who didn't, in two separate columns.</p> <pre><code> train = ...
<p>Make this change in your code <code>whole = pd.concat([train, test]).reset_index(drop=True)</code></p>
python|pandas|dataframe
3
12,291
69,623,616
np.cov calculating covariance matrix: ValueError: m has more than 2 dimensions
<p>I am trying to compute the covariance matrix for three vectors. The vectors are converted into numpy arrays and then the covariance matrix is determined from this.</p> <p>However I get an error:</p> <pre><code>Traceback (most recent call last): File &quot;assignment_1.py&quot;, line 263, in &lt;module&gt; main...
<p>The <code>data</code> numpy matrix will have a shape <code>(3, 11, 1)</code> using the above example, i.e., a dimension of 3. <a href="https://numpy.org/doc/stable/reference/generated/numpy.cov.html" rel="nofollow noreferrer"><code>np.cov</code></a> only accepts arrays of 1 or 2 dimensions thus it is returning an er...
python|pandas|numpy
0
12,292
69,631,645
Merging two csv files with panda.concat
<p>I am trying to merge two csv files using pandas.concat(). These files have the same row and columns structure and I would like to merge one after the other along the rows. For example, the first csv file ('ex1.csv') is</p> <pre><code>Ex1,Ex1 Ex1,Ex1 Ex1,Ex1 Ex1,Ex1 </code></pre> <p>and the second ('ex2.csv') is</p> ...
<p>Assuming the column names are same..</p> <pre><code>dfnew = pd.concat([df1,df2]).reset_index(drop=true) </code></pre>
python|pandas|csv
0
12,293
38,114,104
Training different scikit-learn classifiers on multiple CPUs for each iteration
<p>I have a script that randomly generates a set of data and trains several classifiers to compare them against each other (it's very similar to <a href="http://scikit-learn.org/stable/auto_examples/classification/plot_classifier_comparison.html" rel="noreferrer">http://scikit-learn.org/stable/auto_examples/classificat...
<p>This is less of an answer and more of a rough sketch of an answer to your first question, </p> <blockquote> <p>How would I be able to train the classifiers using different threads <code>for every iteration of for num_samples, num_feats, num_feats_to_remove in product(_samples, _feats, _feats_to_rm)</code></p>...
python|multithreading|numpy|scikit-learn|threadpool
3
12,294
46,294,090
Creating a pandas dataframe from an unknown number of lists of columns
<p>I have limited my requirements to 5 columns and 3 rows for easy explanation. My column header will come to string and my rows will come to a string. I want all the rows to be added to a dataframe. Here is what I have tried</p> <pre><code>import pandas as pd Column_Header = "Col1,Col2,Col3,Col4,Col5" # We have upto...
<p>The best and fastest is create list of all data by <code>list comprehension</code> and call <code>DataFrame</code> constructor only once:</p> <pre><code>Column_Header = "Col1,Col2,Col3,Col4,Col5" Row1 = "Val11,Val12,Val13,Val14,Val15" Row2 = "Val21,Val22,Val23,Val124,Val25" Row3 = "Val31,Val32,Val33,Val34,Val35" r...
python|pandas|dataframe
2
12,295
46,313,624
Pandas: Apply function to each pair of columns
<p>Function <code>f(x,y)</code> that takes two Pandas Series and returns a floating point number. I would like to apply <code>f</code> to each pair of columns in a DataFrame <code>D</code> and construct another DataFrame <code>E</code> of the returned values, so that <code>f(D[i],D[j])</code> is the value of the <code>...
<p>You can avoid explicit loops by using <a href="https://numpy.org/doc/stable/user/basics.broadcasting.html" rel="nofollow noreferrer">Numpy's broadcasting</a>.</p> <p>Combined with <code>np.vectorize()</code> and an explicit signature, that gives us the following:</p> <pre><code>vf = np.vectorize(f, signature='(n),(n...
python|pandas
4
12,296
58,358,192
How to count instances of a specific words in a Dataframe?
<p>I want to count how many times these ngrams appear in a dataframe's column (df.content) full of articles. My dataframe is this:</p> <p><a href="https://i.stack.imgur.com/BYyYI.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BYyYI.jpg" alt="enter image description here"></a></p> <p>and my list of...
<p>Try this:</p> <pre class="lang-py prettyprint-override"><code>df["content"].apply(lambda x: pd.Series({el: x.count(el) for el in ngrams_count})).sum() </code></pre> <p>Sample output:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; lst ['dfo', 'a', 'd0', 'do'] &gt;&gt;&gt; df idx ...
python|pandas
2
12,297
69,010,116
pandas/python: drop duplicates of same strings with different order
<p>is it possible to drop duplicate of rows with the same strings but of different order within the same column?</p> <p>exampe: dl3_hr_rank.r0 and hr_dl3_rank.r0</p> <p>code for df before drop:</p> <pre><code>data = {'item':['dl3_hr_rank.r0','hr_dl3_rank.r0','hr_kl3_rank.r0', 'kl3_hr_rank.r0','hcrfr_hr_...
<p>Try:</p> <pre><code>df[~df.item.str.split('_').apply(frozenset).duplicated(keep='first')] </code></pre> <p>Result df: <a href="https://i.stack.imgur.com/hfmBZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hfmBZ.png" alt="enter image description here" /></a></p> <ul> <li>Use pandas.Series.str.spl...
python|pandas
1
12,298
71,638,178
df.to_csv function prints out the content instead of writing data to a file
<p><code>df.to_csv(output_file)</code> is supposed to write the content of a DataFrame to a file. <strong>While the function is working for 99.9% of the file in my directory</strong>, there is this one file where the function prints out the content of the file instead of writing it to a directory. Then, when I run a <c...
<p>You must be on Windows. This happens because 'CON' is a reserved name (no matter the extension), and Windows will refuse to write a file with such a name to disk.</p>
python|pandas|dataframe|export-to-csv
1
12,299
71,576,257
Reformatting a dataframe to access it for sort after concatenating two series
<p>I've joined or concatenated two series into a dataframe. However one of the issues I'm not facing is that I have no column headings on the actual data that would help me do a sort</p> <pre><code>hist_a = pd.crosstab(category_a, category, normalize=True) hist_b = pd.crosstab(category_b, category, normalize=True) coun...
<p>Just rename the columns of the dataframe, for example:</p> <pre><code>df = pd.DataFrame({0:[1,23]}) df = df.rename(columns={0:'new name'}) </code></pre> <p>If you have a lot of columns you rename all of them at once like:</p> <pre><code>df = pd.DataFrame({0:[1,23]}) rename_dict = {key: f'Col {key}' for key in df.key...
python|pandas
1