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,500
48,051,257
Join two Dataframe table
<p>I have two dataframe table :</p> <p>df1 </p> <pre><code>id A 1 wer 3 dfg 5 dfg </code></pre> <p>df2 </p> <pre><code>id A 2 fgv 4 sdfsdf </code></pre> <p>I want to join this to dataframe for one that will look like that:</p> <p>df3 </p> <pre><code>id A 1 wer 2 fgv 3 dfg </code></pre> <p>...</p>
<pre><code>df3 = df1.merge(df2,how='outer',sort=True) </code></pre>
python|pandas
0
12,501
48,859,167
Subtracting values of attributes within one Pandas Dataframe from another dataframe
<p>This problem contains 3 separate dataframes. df1 represents the 'Total' of products 1,2,3, containing 'value1', 'value2' df2 represents the 'Customer1' of products 1,2,3, containing 'value1', 'value2' df3 represents the 'Customer2' of products 1,2,3, containing 'value1', 'value2'</p> <p>df2 &amp; df3 are essential...
<p>Drop <code>Market</code>, set <code>Product Code</code> as the index, and perform index aligned arithmetic on the product codes. After that, just reset the index and insert <code>Market</code> into the result.</p> <pre><code>df1, df2, df3 = [ df.drop('Market', 1).set_index('Product Code') for df in [df1, df2,...
python|python-3.x|pandas
3
12,502
48,550,960
Combine several excel files from multiple folders and subfolders into one pandas dataframe
<p>My main folder is called "Data". Inside, I have 20 folders labelled from 1 to 20. In each of these 20 subfolders I have another 1 to 5 subfolders and one of them is called "test_results" (the one I am interested in). Inside that test_result folder I have several files, ranging from .jpeg, .csv, .xlxs. I need to work...
<p>Use <a href="https://docs.python.org/3/library/pathlib.html#Path.glob" rel="nofollow noreferrer">pathlib</a> module.</p> <p>Demo:</p> <pre><code>from pathlib import Path p = Path(r'/path/to/Data') df = pd.concat([pd.read_excel(f) for f in p.glob('**/test_results/*.xlsx')], ignore_index=True) </cod...
python|excel|pandas|dataframe|glob
0
12,503
48,645,846
Python's Xgoost: ValueError('feature_names may not contain [, ] or <')
<p>Python's implementation of XGBClassifier <a href="https://github.com/dmlc/xgboost/blob/master/python-package/xgboost/core.py#L667" rel="noreferrer">does not accept</a> the characters <code>[, ] or &lt;'</code> as features names.</p> <p>If that occurs, it raises the following: </p> <blockquote> <p>ValueError('fe...
<p>I know it's late but writing this answer here for other folks who might face this. Here is what I found after facing this issue: This error typically happens if your column names have the symbols <code>[ or ] or &lt;</code>. Here is an example:</p> <pre><code>import pandas as pd import numpy as np from xgboost.skl...
python|pandas|numpy|scikit-learn|xgboost
25
12,504
48,849,540
Random Forest Regression Accuracy different for Training set and Test set
<p>I am new to Machine Learning and to Python. I am trying to build a Random Forest Regression model on one of the datasets from the UCI repository. This is my first ML model. I may be entirely wrong in my approach.</p> <p>The dataset is available here - <a href="https://archive.ics.uci.edu/ml/datasets/abalone" rel="n...
<p>Before trying to answer to your points, a comment: I see you are using a Regressor with accuracy as metric. But accuracy is a metric used in classification problems; in regressions models you usually use other metrics, as Mean Squared Error (MSE). See <a href="http://scikit-learn.org/stable/modules/model_evaluation....
python|machine-learning|scikit-learn|regression|sklearn-pandas
12
12,505
48,673,428
Python Pandas Pairwise Frequency Table with many columns
<p>Beginner Pandas Question here:</p> <p><strong>How do I create a cross frequency count table for all columns?</strong> I want to ues the output to make a seaborn heatmap plot showing the counts between each pair of columns.</p> <p>I have a dataframe (pulled down from hdfs with pyspark) with ~70 unique columns and a...
<p>Clip positive values to <code>1</code> with <code>clip_upper</code>, and then compute the dot product:</p> <pre><code>i = df.clip_upper(1) j = i.T.dot(i) </code></pre> <p></p> <pre><code>j C1 C2 C3 C4 C1 3 1 1 2 C2 1 2 0 2 C3 1 0 2 1 C4 2 2 1 4 </code></pre>
python|pandas|numpy|crosstab
3
12,506
70,748,223
Appending list with highest value from two columns using for loop in pandas
<p>I have two columns: column A, and column B.</p> <p>I would like to find whether the value in each row of column A is larger than the value for the same row in column B, and if it is append a list with these values.</p> <p>I'm able to append the list if the value in column A is higher than a set value, but I'm unsure...
<p>An approach could be:</p> <pre><code>import pandas as pd df = pd.DataFrame({&quot;A&quot;:[2, 3, 4, 5], &quot;B&quot;:[1, 4, 6, 3]}) # Test DataFrame print(list(df[df[&quot;A&quot;] &gt; df[&quot;B&quot;]][&quot;A&quot;])) </code></pre> <p><strong>OUTPUT</strong></p> <pre><code>[2, 5] </code></pre> <p><strong>FOLL...
python|pandas|list|for-loop
0
12,507
71,056,432
How to sort x-axis label and legends in python plotly express?
<p><strong>Sorting X-axis labels</strong></p> <p>I have a python dict containing list of dicts which I am flattening and sorting using pandas dataframe in wide-form. What I expect to see in the plotly figure is that the x axis labels to be grouped and sorted with respect to year and period. The period here could take r...
<p>You were headed in the right direction, just need use <code>category_orders</code> instead of <code>categoryorder</code>, and define the order of data using <code>sorted()</code> method.</p> <pre><code>df_normalized = pd.json_normalize(response_dict['data']) df_normalized['Mission'] = df_normalized[['machineType', '...
python|pandas|plotly|plotly-python
0
12,508
71,070,451
delete number column in pandas
<p>Can you help me with removing number in read_csv pandas? For example I want <a href="https://i.stack.imgur.com/9aSVB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9aSVB.png" alt="enter image description here" /></a></p> <p>turn into <a href="https://i.stack.imgur.com/CwdJN.png" rel="nofollow no...
<p>That's the index, and you can't get rid of it unless you make another column the index, which you can do with <code>df = df.set_index('your column')</code>.</p>
python|pandas
1
12,509
51,652,404
Calculating rolling sum in a pandas dataframe on the basis of 2 variable constraints
<p>I want to create a variable : <strong>SumOfPrevious5OccurencesAtIDLevel</strong> which is the sum of previous 5 values (as per Date variable) of <strong><em>Var1</em></strong> at an ID level (column 1) , otherwise it will take a value of NA</p> <p>Sample Data and Output:</p> <pre><code>ID Date Var1 SumOfPre...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow noreferrer"><code>transform</code></a> and...
python-3.x|pandas
1
12,510
51,681,777
Pandas/Pythonic way to groupby a column X, within each group, return value in column Y based on value in column Z
<p>Reproducible example:</p> <pre><code>df = pd.DataFrame([[1, '2015-12-15', 10], [1, '2015-12-16', 13], [1, '2015-12-17', 16], [2, '2015-12-15', 19], [2, '2015-12-11', 22], [2, '2015-12-18', 25], [3, '...
<p>IIUC</p> <pre><code>g1=df.groupby('X').Y.value_counts().count(level=1).eq(df.X.nunique()) # get group1 , all date should show in three groups , we using value_counts df.Y=pd.to_datetime(df.Y) # change to date format in order to sort g2=df.sort_values('Y').groupby('X').head(1) # get the min date row . pd.concat([d...
python|python-3.x|pandas|pandas-groupby
2
12,511
51,617,492
Pandas Data Cleaning
<p>So I'm reading tables from a PDF into a pandas dataframe, but I'm still pretty new to pandas, and it is pretty daunting going through the documentation. I'm sure there is a fairly easy way to do what I need to, but I just don't know how.</p> <pre><code> 0 1 2 3 ...
<p>For the first point, you can try this:</p> <pre><code>df = df.T df.iloc[:,-1] = df.iloc[:,-1].shift(1) df = df.T df = df.drop(df.columns[0], axis=1) </code></pre> <p>For the last point:</p> <pre><code>df['1'] = df['1'].ffill() </code></pre>
python-3.x|pandas|dataframe|pdf
1
12,512
51,842,993
confusion in different ways to open a session and executing the graph in tensorflow
<p>I am trying to learn deep learning with tensorflow, so excuse my stupid questions. I have been reading different tutorials as '<a href="https://github.com/Hvass-Labs/TensorFlow-Tutorials" rel="nofollow noreferrer">https://github.com/Hvass-Labs/TensorFlow-Tutorials</a>' and '<a href="https://github.com/u04617/deeplea...
<p>Both are working. </p> <ul> <li>In Jupyter Notebook files: use <code>InteractiveSession</code></li> </ul> <p>Read <a href="https://stackoverflow.com/q/50229091/7443104">here</a> to understand the difference between an <code>InactiveSession</code> and a <code>Session</code>. But do not even try <code>eval()</code>....
session|tensorflow|neural-network
1
12,513
41,981,921
How do i show the proper count value in seaborn?
<pre><code>CH Gayle 17 YK Pathan 16 AB de Villiers 15 DA Warner 14 SK Raina 13 RG Sharma 13 MEK Hussey 12 AM Rahane 12 MS Dhoni 12 G Gambhir 12 </code></pre> <p>I have a series like this. I want to plot the player on the x axis and their resp...
<p><code>sns.countplot</code> is meant to do the counting for you. You are counting yourself with <code>value_counts</code> then plotting the counts of counts. Pass <code>matches</code> directly to <code>sns.countplot</code></p> <pre><code>ax = sns.countplot(matches['player_of_match'], color='B') plt.sca(ax) plt.xti...
python|pandas|matplotlib|seaborn|data-analysis
4
12,514
42,115,950
Consolidating two data frames in Python
<p>How to overlay/consolidate two data frames in python, such that overlapping cells (index,column) get added and uncommon cells preserve the values from original data frame?</p> <p>This is possible in Excel as explained <a href="https://support.office.com/en-us/article/Consolidate-multiple-worksheets-into-one-PivotTa...
<p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.add.html" rel="nofollow noreferrer"><code>add</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="nofollow noreferrer"><code>fillna</code></a>, but in <code>df1</code...
python|pandas|dataframe
1
12,515
64,313,883
pandas df to dict with groupby
<p>I have this df :</p> <pre><code>line stop 1 1_a 1 1_b 1 1_c 2 2_a 2 2_c </code></pre> <p>I want to create the following dict :</p> <p><code>d={1 : {&quot;stops&quot; : &quot;1_a&quot;,&quot;1_b&quot;,&quot;1_c&quot;}, 2 : {&quot;stops&quot; : &quot;2_a&quot;,&quot;2_b&quot;,&quot;2_c&quot;}}</code><...
<p>You could avoid the <code>to_dict</code> part and iterate through the grouping to get your dictionary, since you are not doing any computations :</p> <pre><code>{key: {&quot;stops&quot;: &quot;,&quot;.join(value.stop.array)} for key, value in df.groupby(&quot;line&quot;)} {1: {'stops': '1_a,1_b,1_c'}, 2: {'stops'...
python|pandas|dataframe|dictionary
1
12,516
64,185,545
Select exact match in pandas row or with combined search terms
<p>first question here so apologies if there are any mistakes or unclear points!</p> <p>I am trying to develop a sort of search engine to look through some tabular data in a pandas dataframe, but am getting partial matches included in the search.</p> <p>For example, I have a table with the following values:</p> <pre><c...
<p>You can use this:</p> <p>df_search_2 = df_search[df_search['style'] == 'House']]</p>
python|pandas
0
12,517
64,327,397
In Transfer Learning ValueError: Failed to convert a NumPy array to a Tensor
<p>I am Practicing on <strong>Transfer Learning</strong> with Iris dataset.</p> <p>For the following code I get the following error messege:</p> <blockquote> <p>Failed to convert a NumPy array to a Tensor (Unsupported object type float)</p> </blockquote> <p>I Need help in solving this error.</p> <blockquote> <p>Below t...
<p>You can try the following:</p> <pre><code>X = np.asarray(x).astype(np.float32) model_fit=model.fit(X,y, verbose=2, epochs=10, steps_per_epoch=3) </code></pre> <p>It seems that one of the column is not supported. So just convert it to numpy array with data type float.</p> <p>Note you define <code>x</code> in a wrong...
python|numpy|tensorflow|deep-learning|transfer-learning
1
12,518
64,506,980
I can't get FER to work with the example code
<p>I want to use FER just for fun and to tinker with but after i have installed it i am trying to run the example code and i am getting this error could someone more educated please help me.</p> <p>Latest Tensorflow version, Windows 10 Pro, Python 3.8.6 64bit</p> <p><a href="https://github.com/justinshenk/fer" rel="nof...
<p>Are you using Anaconda or Miniconda? Try to install tensorflow + fer in your local machines, without using enviroements, it worked for me.</p>
python|python-3.x|tensorflow|face-recognition
0
12,519
64,378,767
Calculate the sum of the first n rows for each group
<p>What I want to do is group by column A and then take the sum of first two rows, then assign that value as a new column. Example below:</p> <p>DF:</p> <pre><code>ColA ColB AA 2 AA 1 AA 5 AA 3 BB 9 BB 3 BB 2 BB 12 CC 0 CC 10 CC 5 CC 3 </code></...
<p>You can use <code>transform</code> to get a new value per each row and a lambda function. In <code>lambda</code> you can use <code>head(2)</code> to get first 2 rows for each group and <code>sum()</code> them:</p> <pre><code>df.groupby('ColA')['ColB'].transform(lambda x: x.head(2).sum()) </code></pre>
python|pandas|dataframe
6
12,520
64,407,738
How to show every layer in keras?
<p>I have a very easy model in keras. I defined a function to get vgg19 network and then connect it with a flatten layer and then a dense layer. When I print the model summary, it does not show every layer in the vgg19 network. Is there any way to show that without changing the function about vgg19? Any advice is appre...
<p>You can use the method get_layer(name, index) on your model type. you can find more information about it here <a href="https://www.tensorflow.org/api_docs/python/tf/keras/Model#get_layer" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/keras/Model#get_layer</a></p> <p>for your code, you can u...
python|tensorflow|keras|deep-learning|neural-network
1
12,521
47,548,145
Understanding tensorflow inter/intra parallelism threads
<p>I would like to understand a little more about these two parameters: intra and inter op parallelism threads</p> <pre><code>session_conf = tf.ConfigProto( intra_op_parallelism_threads=1, inter_op_parallelism_threads=1) </code></pre> <p>I read this post which has a pretty good explanation: <a href="https://stack...
<ol> <li><p>When both parameters are set to 1, there will be 1 thread running on 1 of the 4 cores. The core on which it runs might change but it will always be 1 at a time.</p></li> <li><p>When running something in parallel there is always a trade-off between lost time on communication and gained time through paralleli...
tensorflow
5
12,522
49,005,874
First training epoch is very slow
<p>Hi… I’m running mnist code in my P3 AWS machine and the initialization process seems to be very long compared to my previous P2 machine (although P3>P2)</p> <pre><code>Train on 60000 samples, validate on 10000 samples Epoch 1/10 60000/60000 [==============================] - 265s 4ms/step - loss: 0.2674 - acc: 0.91...
<p>Based on this <a href="https://github.com/keras-team/keras/issues/6503" rel="nofollow noreferrer">issue</a>:</p> <blockquote> <p>The first epoch takes the same time, but the counter also takes into account the time taken by building the part of the computational graph that deals with training (a few seconds)....
tensorflow|deep-learning|keras|mnist
3
12,523
49,013,318
How to aggregate columns of sets?
<p>I have a pandas datafame where the rows in a particular column are sets of id's. I would like to aggregate across a 15min period and find all such unique id's.</p> <pre><code>timestamp | ids | some_int 00:03:00 {id1, id2, id3} 5 00:10:00 {id2, id4, id7, id10} 9 00:25:00 ...
<p>Change <code>set</code> to <code>list</code> then using <code>sum</code> </p> <pre><code>df.ids=df.ids.apply(list) s=df.resample('15min').agg({'ids': 'sum', 'some_int': 'sum'}) s.loc[s.ids.eq(False),'ids']='' s.ids=s.ids.apply(set) s Out[134]: ids some_int timestam...
python|python-3.x|pandas|dataframe
2
12,524
49,032,948
Flatten numpy array with sub-arrays of different dimensions
<p>This seems like a simple enough task, but I haven't found how to do it using <code>numpy</code>. Consider the example array:</p> <pre><code>import numpy as np aa = np.array([np.array([13.16]), np.array([1.58 , 1.2]), np.array([13.1]), np.array([1. , 2.6])], dtype=object) </code></pre> <p>I need a general way to fl...
<p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.hstack.html" rel="noreferrer"><code>numpy.hstack</code></a></p> <pre><code>&gt;&gt;&gt; np.hstack(aa) array([13.16, 1.58, 1.2 , 13.1 , 1. , 2.6 ]) </code></pre>
python|arrays|numpy
21
12,525
49,052,420
Getting shape not aligned error sklearn .
<pre><code>import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression Dataset = pd.read_csv('Salary_Data.csv') Salary , YearsExperience = Dataset['Salary'] ,Dataset['YearsExperience'] X_train, X_test, y_train, y_test = train_test_split(YearsExperience , ...
<p>If you don't reshape your data at all sklearn gives you a hint:</p> <pre><code>Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample. </code></pre> <p>As your data has a single feature, you have to reshape it to (-1, 1) instead ...
python|machine-learning|scikit-learn|linear-regression|sklearn-pandas
1
12,526
49,050,306
Keras shape error - im inputting the shape its asking for
<p>I wanted to write a simple function to load a keras model from json and run a prediction. However everytime I run it i get the following error:</p> <pre><code>ValueError: Error when checking : expected input_2 to have shape (28,) but got array with shape (1,) </code></pre> <p>The code below shows i've printed out ...
<p>Your model has been initialized (and trained) to receive input from a shape (N,28) matrix. It expects 28 columns.</p> <p>The way to fix this is to reshape your single input row to match:</p> <pre><code>z = z[:, np.newaxis].T #(1,28) shape </code></pre> <p>Or:</p> <pre><code>z = z.reshape(1,-1) #reshapes to (1,wh...
python|json|numpy|keras
1
12,527
58,925,808
python IndexError: boolean index did not match indexed array along dimension 0; dimension is 32 but corresponding boolean dimension is 112
<p>i am new to matploblib and numpy and have faced issues trying to extracting the data. the following codes results in IndexError: boolean index did not match indexed array along dimension 0; dimension is 32 but corresponding boolean dimension is 112. pls advise!! </p> <p>dataset used: <a href="https://data.gov.sg/da...
<p>you have few issues here..</p> <p>first one don't use python keywords as variables change this to</p> <pre><code>type = np.unique(data['type']) </code></pre> <p>this</p> <pre><code>types = np.unique(data['type']) </code></pre> <p>your error is you are trying to compare boolean array which have 112 values(data) ...
python|numpy
0
12,528
58,893,823
Grad is very small
<p>First I thought, there is no update after the loss calculation and update step but the follwing code gives me false which prove there is an update:</p> <pre><code>before = list(model.parameters())[0].clone() loss.backward() optimizer.step() after = list(model.parameters())[0].clone() logging.info(torch.equal(before...
<p>You can add the parameters up, to see, how much they change each time the optimizer is called. Therefore you can use a function like this.</p> <pre><code>def read_params(self): params=[] names=[] for name,param in self.lstm.named_parameters(): params.append(torch.sum(param.data).detach().cpu().n...
python|optimization|deep-learning|pytorch|lstm
0
12,529
58,696,121
How to merge two columns under certain conditions in a third one
<p>I am rather new to Pandas and I struggle to solve this problem :</p> <p>I have a DataFrame with doctors' activities. </p> <pre><code>pd0.info() ...
<p>you can use a simple apply here : </p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'code_practicien':['BENYY00','BENY00','GAUD00','SAVO01'],'code_anesthesiste':['MORA01','MORA01',np.NaN,'SAVO01']}) df['anethesite']=df.apply(lambda row: row['code_practicien'] if (pd.isnull(row['code_anesthesis...
python|pandas
1
12,530
58,759,949
Creating a variable using conditionals python using vectorization
<p>I have a pandas dataframe as below,</p> <pre><code> flag a b c 0 1 5 1 3 1 1 2 1 3 2 1 3 0 3 3 1 4 0 3 4 1 5 5 3 5 1 6 0 3 6 1 7 0 3 7 2 6 1 4 8 2 2 1 4 9 2 3 1 4 10 2 4 1 4 </code></pre> <p>I want to create a column 'd' b...
<p>Here's how I would translate your logic:</p> <pre><code>df['d'] = np.nan # first row of flag s = df.flag.ne(df.flag.shift()) # where a &gt; c a_gt_c = df['a'].gt(df['c']) # fill the first rows with a &gt; c df.loc[s &amp; a_gt_c, 'd'] = df['b'] # mask for second fill mask = ((~s) ...
python-3.x|pandas
0
12,531
70,068,490
How can I make pretty dataframe using json file in python?
<p>I've try to save the data that I received from Open API.</p> <pre><code>import requests import pandas as pd import json from pandas import DataFrame def Bring_API(): url = &quot;api_url/authenticate key/options&quot; response = requests.get(url) data = response.json() print(data) Bring_API() </code>...
<p>Maybe you can load it as a JSON file. Using json module, json.load()</p> <p>and then passing to pandas dataframe only what you want as a table:</p> <pre><code>df = pd.DataFrame(data[&quot;COOKRCP01&quot;][&quot;row&quot;]) </code></pre> <blockquote> <p>LS RCP_WAY2 ... MANUAL13 MANUAL14 0 sweet potato soup\nsweet p...
python|pandas|dataframe|api
0
12,532
70,297,751
Within a loop, match items with values in a dataframe column, then store a separate column value as a variable
<p>I have an existing loop that I am using to go through a large amount of file paths, which ultimately sends the files through a cloud processing pipeline. I need to update the loop to match the file names with a dataframe column (<code>fileName</code>), then get the associated data values from a second column (<code>...
<p>Change this code:</p> <pre><code>if fbname in df['fileName']: year = df['date'] print('Collection date: ',year) </code></pre> <p>to this:</p> <pre class="lang-py prettyprint-override"><code>if df['fileName'].isin([fbname]).any(): year = df['date'][df['fileName'] == fbname].iloc[0] print('Collection d...
python|pandas|dataframe|loops
0
12,533
70,321,319
Pandas does not show first column
<p>I have a couple of function which filter a dataframe of different customers' features and return the filtered dataframe as below:</p> <pre><code>stg_1 = strategy_1_filtering(df_1) stg_2 = strategy_2_filtering(df_2) </code></pre> <p>Now, I make an adjacency matrix to based on Customer IDs and strategies:</p> <pre><co...
<p>Your first column is actually an index. Use <code>rename_axis</code>:</p> <pre><code>df = df.rename_axis('Customer ID') </code></pre> <p>If you want the index as column, use <code>reset_index</code>:</p> <pre><code>df = df.rename_axis('Customer ID').reset_index() </code></pre>
python|pandas|rename
2
12,534
70,087,794
Convert TZ datetime to timestamp
<p>I have column of dates in the format below in a pandas dataframe.</p> <p>What is the most effective way to convert</p> <p>2021-11-06T21:54:35.825Z</p> <p>to</p> <p>2021-11-6 21:54:35</p> <pre><code>pd.to_datetime(df['date'], format='%Y-%m-%d %H:%M:%S') only returns 2021-11-06 without the timestamp </code></pre>
<p>You can use <code>.dt</code> accessor on Pandas Series followed by by <code>.strftime</code> property <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.dt.strftime.html" rel="nofollow noreferrer">dt.strftime</a>, to format datetime into desired string representation.</p> <pre><code>import pandas as...
pandas|dataframe|timestamp
0
12,535
70,159,727
Reformatting DataFrame so that alternating rows are in same row
<p>I have a dataframe that lists trading activity in subsequent rows. So row 1 is the information for the buy, and row 2 is the information for the sell, and so on.</p> <p>Ideally I'd like to see the info for each buy/sell pair in the same row. Normally I'd use <code>pivot_table</code> or <code>pivot</code> to do som...
<p>Try:</p> <ol> <li>Assign an &quot;idx&quot; corresponding to the trade number for every 2 rows</li> <li>Assign the &quot;action&quot; based on the &quot;Signal&quot;</li> <li><code>pivot</code> to get the required structure</li> <li><code>rename</code> columns to desired values</li> </ol> <pre><code>values[&quot;idx...
python|pandas|dataframe
2
12,536
56,217,454
Error while converting pytorch model to core-ml
<pre><code>C = torch.cat((A,B),1) </code></pre> <p>shape of tensors: </p> <pre><code>A is (1, 128, 128, 256) B is (1, 1, 128, 256) </code></pre> <p>Expected <code>C</code> value is <code>(1, 129, 128, 256)</code></p> <p>This code is working on pytorch, but while converting to core-ml it gives me below error:</p> <...
<p>It was coremltools version related issue. Tried with latest beta coremltools 3.0b2.</p> <p>Following works without any error with latest beta.</p> <pre><code>import torch class cat_model(torch.nn.Module): def __init__(self): super(cat_model, self).__init__() def forward(self, a, b): c = t...
pytorch|onnx|onnx-coreml
0
12,537
56,285,730
how to fill in the missing values using the previous and post values
<p>If my data is:</p> <pre><code>a=pd.DataFrame({'Array1':[None,1,2,None,3,None,4,5,6,None]}) </code></pre> <p>I want to fill in the missing values so that the data is:</p> <pre><code>1,1,2,2.5,3,3.5,4,5,6,6 </code></pre> <p>You can see that the first missing value is filled as 1 because the second value is 1, whic...
<p>Check with <code>interpolate</code></p> <pre><code>a.interpolate(method ='linear',limit_direction ='both') Out[502]: Array1 0 1.0 1 1.0 2 2.0 3 2.5 4 3.0 5 3.5 6 4.0 7 5.0 8 6.0 9 6.0 </code></pre>
python|pandas|interpolation|mean
2
12,538
56,115,030
Converting TfidfVectorizer's fit_transform variable to an array (.toarray()) makes everything zero?
<p>I'm experimenting with tfidf with a sample dataset, and everything is working fine up until I convert my fit-transofrm variable to an array. I am trying to view my "features" after using tfidf, and the values make sense when i print it. However, when i print it as an array, then all values become zero for some reaso...
<p>I discovered that I am testing it incorrectly, there are actually some values after knowing more about the tf-idf matrix, each word has its own column, so only the words that are unhique in the document will have a value in the matrix, they are NOT all zeros.</p>
python|pandas|machine-learning|scikit-learn
0
12,539
55,719,276
Linear Regression on each column without creating for loops or functions
<p>Applying regression on each of the columns or rows in a pandas dataframe, without using for loops.</p> <p>There is a similar post about this; <a href="https://stackoverflow.com/questions/47635210/apply-formula-across-pandas-rows-regression-line">Apply formula across pandas rows/ regression line</a>, that does a reg...
<p>Look at the following example:</p> <pre><code>import numpy as np import pandas as pd from scipy.stats import linregress np.random.seed(1997) df = pd.DataFrame(pd.np.random.rand(100, 10)) df.apply(lambda x: linregress(df.index, x), result_type='expand').rename(index={0: 'slope', 1: ...
python|pandas|scipy|regression
4
12,540
55,749,202
Getting gradient of vectorized function in pytorch
<p>I am brand new to PyTorch and want to do what I assume is a very simple thing but am having a lot of difficulty. </p> <p>I have the function <code>sin(x) * cos(x) + x^2</code> and I want to get the derivative of that function at any point. </p> <p>If I do this with one point it works perfectly as </p> <pre><code>...
<p><a href="https://discuss.pytorch.org/t/loss-backward-raises-error-grad-can-be-implicitly-created-only-for-scalar-outputs/12152" rel="noreferrer">Here</a> you can find relevant discussion about your error.</p> <p>In essence, when you call <code>backward()</code> without arguments it is implicitly converted to <code>...
python|pytorch|derivative|autodiff
7
12,541
56,009,635
tf.keras & tf.estimator & tf.dataset
<p>I am trying to update my code to work with TF 2.0. as a start, I have used a pre-made keras model:</p> <pre><code>def train_input_fn(batch_size=1): """An input function for training""" print("train_input_fn: start function") train_dataset = tf.data.experimental.make_csv_dataset(CSV_PATH_TRAIN, batch_size=bat...
<p>You don't need this line</p> <pre><code> train_dataset = train_dataset.repeat().batch(batch_size) </code></pre> <p>Function you're using to create dataset, <code>tf.data.experimental.make_csv_dataset</code> alredy batched it. You can use <code>repeat</code> though </p>
python|tensorflow|keras|tensorflow-datasets|tensorflow-estimator
1
12,542
64,927,469
Keras input layer
<p>I am unsure if I need to add a Dense input layer before adding LSTM layers in my model. Forexample, with the following model:</p> <pre><code># Model model = Sequential() model.add(LSTM(128, input_shape=(train_x.shape[1], train_x.shape[2]))) model.add(Dense(5, activation=&quot;linear&quot;)) </code></pre> <p>Will the...
<p>You don't need too. It depends on what you want to accomplish.</p> <p>Check <a href="https://machinelearningmastery.com/timedistributed-layer-for-long-short-term-memory-networks-in-python/" rel="nofollow noreferrer">here</a> some cases.</p> <p>In your case, yes the LSTm will be the first layer and the Dense layer wi...
tensorflow|keras
0
12,543
64,932,778
Filter using a for loop and return multiple data frames in python
<p>I have a df that looks like that:</p> <pre><code>+--------+------------+-------+ | Fruit | Date | Sales | +--------+------------+-------+ | Apple | 01/01/2020 | 20 | | Apple | 01/02/2020 | 30 | | Orange | 01/01/2019 | 55 | | Orange | 01/02/2018 | 15 | +--------+------------+-------+ </code></pre...
<p>I hope you are trying to create multiple dataframe names as same as the unique fruit names.</p> <p>The below code snippet will not work as the variable <code>fruit</code> is being replaced as <code>pd.DataFrame()</code> and will not be &quot;Apple&quot; or &quot;Orange&quot;</p> <pre><code>for fruit in fruits: fru...
python|pandas|loops
1
12,544
64,899,507
copying specific elements from array
<p>I have an array like <code>[10,11,12,13,14,15,16,17,18,19]</code> and I'm looking for a way to take the <code>[1,4,5]</code> position elements from the array to a new array for example. So in this case the new array would be <code>[11,14,15]</code></p> <p>is there a neat way of doing this without running through a l...
<pre><code>new_arr = numpy.array([10,11,12,13,14,15,16,17,18,19])[[1,4,5]] </code></pre>
python|python-3.x|numpy
0
12,545
65,023,174
Pandas Dataframe to Apache Beam PCollection conversion problem
<p>I'm trying to convert a pandas DataFrame to a PCollection from Apache Beam. Unfortunately, when I use <code>to_pcollection()</code> function, I get the following error:</p> <pre><code>AttributeError: 'DataFrame' object has no attribute '_expr' </code></pre> <p>Does anyone know how to solve it? I'm using pandas=1.1.4...
<p><code>to_pcollection</code> was only ever intended to apply to Beam's deferred Dataframes, but looking at this it makes sense that it should work, and isn't obvious how to do manually. <a href="https://github.com/apache/beam/pull/14170" rel="nofollow noreferrer">https://github.com/apache/beam/pull/14170</a> should ...
python|pandas|dataframe|apache-beam
1
12,546
40,054,615
How to create a DataFrame series as a sub-string of a DataFrame Index?
<p>I have a Pandas DataFrame which has a 5-digit string as its index (the index is a 5 digit zip code). I'd need to create another series in the DataFrame which is the first three characters of the index (i.e. the 3-Digit zip code).</p> <p>As an example, if the index for a row is "32779", I'd like the new series' valu...
<p>The bracket operator on strings is exposed through <code>str.slice</code> function:</p> <pre><code>fte5.index.astype(str).str.slice(0,3) </code></pre>
python|pandas|dataframe
2
12,547
43,971,649
dump weights of cnn in json using keras
<p>I want to use the dumped weights and model architecture in other framework for testing. </p> <p>I know that:</p> <ul> <li><code>model.get_config()</code> can give the configuration of the model</li> <li><code>model.to_json</code> returns a representation of the model as a JSON string, but that the representation d...
<p>Keras does not have any built-in way to export the weights to JSON.</p> <p><strong>Solution 1:</strong></p> <p>For now you can easily do it by iterating over the weights and saving it to the JSON file.</p> <pre><code>weights_list = model.get_weights() </code></pre> <p>will return a list of all weight tensors in ...
json|tensorflow|keras|conv-neural-network
8
12,548
69,528,161
Dividing two columns in a dataframe based on condition
<p>I have the below dataframe:</p> <pre><code>|module | name |value | |-----------|-------|------| |node[11] | x |4.0 | |node[11] | y |1.0 | |node[2] | x |2.0 | |node[2] | y |3.0 | |node[21] | x |6.0 | |node[21] | y |6.0 | </code></pre> <p>and would like to create ...
<p>You can just do <code>pivot</code> then calculated what your need</p> <pre><code>out = df.pivot(*df).eval('x/y').to_frame('out').reset_index() Out[23]: module out 0 node[11] 4.000000 1 node[21] 1.000000 2 node[2] 0.666667 </code></pre>
python|pandas|dataframe
5
12,549
41,111,632
feed picture to model tensorflow for training
<p>I'm trying to import pictures to my model for training just like example "<strong>image_retraining</strong>" : <a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/image_retraining" rel="nofollow noreferrer">https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/image_r...
<p>One way is to load them yourself using PIL or OpenCV e.g. <code>cv2.imread(filename.png)</code>, and then give them to your graph (in <code>feed_dict</code>) as an array with dimensions [<code>number of images (batch size), height, width, channels (3 if RGB)]</code>.</p>
python|tensorflow
0
12,550
41,197,988
Concatenate several Date Columns and column values in Python
<blockquote> <p>Actual .CSV datafile.</p> </blockquote> <pre><code>Date MTM_B7_1 Date MTM_B7_11 Date MTM_B7_12 03/01/11 AM 2084 04/01/11 AM -8166 04/01/11 AM -8332 04/01/11 AM -9066 05/01/11 AM 28613 05/01/11 AM -8750 05/01/11 AM 103607 06/01/11 AM 35605 06/01/11 AM -21307 10/01/11 AM 68538...
<p>Consider splitting dataframe by Date/MTM pairs to a dataframe list and then chain merge outer joins with <code>reduce()</code>:</p> <pre><code>from functools import reduce import pandas as pd df = pd.DataFrame({'Date': pd.date_range('01/03/11',periods=8, format=' %d/%m/%y'), 'MTM1': [2, 3, 4, 5,...
python|pandas
1
12,551
41,123,500
Plotting Probability Density Function with Z scores on pandas/python
<p>with this code : </p> <pre><code>df1 = (df.ix[:,1:] - df.ix[:,1:].mean()) / df.ix[:,1:].std() </code></pre> <p>I calculated z scores on one column with frequency distribution of items from my grouped dataframe on the second column. Now the result looked something like this : </p> <pre><code>Z Score Frequency ...
<p><em>Preparing a dummy data:</em></p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt plt.style.use('fivethirtyeight') np.random.seed([314, 42]) df = pd.DataFrame(dict(ZScore=np.sort(np.random.uniform(-2, 2, 50)), FreqDist=np.random.randint(1, 30, 50))) df.h...
python|pandas|matplotlib|plot
2
12,552
53,997,862
Pandas groupby two columns and plot
<p>I have a dataframe like this:</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline df = pd.DataFrame({'category': list('XYZXY'), 'B': range(5,10),'sex': list('mfmff')}) </code></pre> <p>I want to plot count of sex male or female based on category from column 'cate...
<h1>Various Methods of Groupby Plots</h1> <h2>Data</h2> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd df = pd.DataFrame({'category': list('XYZXY'), 'sex': list('mfmff'), 'ThisColumnIsNotUsed': range(5,10)}) df category sex ThisColumnIsNotUs...
python|pandas|bar-chart
27
12,553
53,897,171
Python - Tensor Flow Error, Tensor must be from the same graph
<p>I have a conv_net function defined in my data_split file like this,</p> <pre><code>def conv_net(X, weights, biases, dropout): X = tf.reshape(X, shape=[-1, HEIGHT, WIDTH, NETWORK_DEPTH]) #error occurs on the below line - while calling the function in debugging mode conv1 = conv2d('conv1', X, weights['conv_we...
<p>Somewhere in the <code>data_split.py</code> file or in the "other" <code>.py</code> file you have a <code>tf.Graph()</code> definition.</p> <p>You defined the model in a graph, something like:</p> <pre><code>g1 = tf.Graph() with g1.as_default(): model = conv_net(data_split.X) </code></pre> <p>But the <code>da...
python|tensorflow
0
12,554
66,261,764
TypeError: classification_report() got an unexpected keyword argument 'output_dict'
<p>I have some code that is applying the random forest algorithm in order to predict the value of the gold column based on the remaining columns.</p> <p>My input file is under the form:</p> <pre><code>gold,MethodType,CallersT,CallersN,CallersU,CallersCallersT,CallersCallersN,CallersCallersU,CalleesT,CalleesN,CalleesU,C...
<p>The problem is that you may have an outdated version of sklearn. Here you can find a explanation how to check your version:</p> <p><a href="https://stackoverflow.com/questions/52740089/how-to-get-output-of-sklearn-metrics-classification-report-as-a-dict#52898079">How to get output of sklearn.metrics.classification_r...
python|pandas|variables
1
12,555
66,161,770
How to check if all columns of a pandas dataframe are equal to a given value
<p>I have a dataframe as:</p> <pre><code>x_data y_data 2.5 2.5 2.5 2.5 2.5 2.5 2.5 2.5 </code></pre> <p>How do i know that all values of these columns are equal to 2.5</p> <p>like if I write: if <code>all(df==2.5)</code></p> <p>answer should be : 1 1</p>
<ul> <li>The <a href="https://docs.python.org/3/library/functions.html" rel="nofollow noreferrer">built-in</a> python function, <a href="https://docs.python.org/3/library/functions.html#all" rel="nofollow noreferrer"><code>all()</code></a>, does not allow for selecting an index along which to compare values.</li> <li>U...
pandas|dataframe
1
12,556
52,680,738
Transform a dataframe based on its datetime index
<p>I have the following dataframe:</p> <pre><code>date = ['2014-02-03 23:00:00','2015-02-03 23:30:00','2015-02-04 00:00:00','2016-02-04 01:30:00'] value = [33.24 , 31.71 , 34.39 , 34.49 ] df = pd.DataFrame({'value':value,'index':date}) df.index = pd.to_datetime(df['index'],format='%Y-%m-%d %H:%M') df.drop(['inde...
<p>You can do:</p> <pre><code>pd.pivot(df.index,df.index.year, df.value) index 2014 2015 2016 index 2014-02-03 23:00:00 33.24 NaN NaN 2015-02-03 23:30:00 NaN 31.71 NaN 2015-02-04 00:00:00 NaN 34.39 NaN 2016-02-04 01:30:00 NaN NaN 34.49...
python|pandas|datetime
1
12,557
46,516,882
Pandas: fillna every columns with some value
<p>I have dataframe and there are <code>NaN</code> values:</p> <pre><code>col1 col2 col3 234 NaN 1 NaN NaN 18 9 2 NaN </code></pre> <p>I have list with values [12, 15, 3] and I need to fill this columns:</p> <p>Desire output</p> <pre><code>col1 col2 col3 234 15 1 12 15 ...
<p>Build a dict of those , then <code>fillna</code></p> <pre><code>l1= [12, 15, 3] df.fillna(dict(zip(df.columns,l1))) Out[120]: col1 col2 col3 0 234.0 15.0 1.0 1 12.0 15.0 18.0 2 9.0 2.0 3.0 </code></pre>
python|pandas
4
12,558
46,385,974
why tensorflow linear regression predict all 0?
<p>I want to realize a linear regression using tensorflow. But I don't know what's wrong with it. If I only train once, the predict result will all be 0. And if I train more, the loss increase instead of decrease. Can anyone help me? Thanks a lot!</p> <pre><code># Step2 x = tf.placeholder(tf.float64, [None, 14]) y_...
<p>What data did you use to train the model? Try decreasing the step value of gradient descent optimizer = tf.train.GradientDescentOptimizer(0.01).minimize(loss) and run it for 1000 times maybe or more</p>
python|machine-learning|tensorflow|linear-regression|gradient-descent
0
12,559
69,181,104
Creatine New Column Based on JSON List
<p>I have the following dataset.</p> <pre><code> details USA [{'country': 'USA', 'city': 'NYC'}] India [{'country': 'India', 'city': 'Mumbai'}] Canada [{'country': 'Canada', 'city': 'VC'}] </code></pre> <p>I need to create a new column named <code>city</code>. I'm trying the following code sn...
<p>The data type of <code>details</code> column is of <code>str</code> type, not <code>dict</code> type. What needs to be done here is that the <code>details</code> column first needs to be parsed via <code>json.loads</code> and then you can get the value of with <code>city</code> key.</p> <p>You will need to replace s...
python|json|pandas|string|dataframe
1
12,560
69,222,605
Python: how select pandas rows based on condition on other columns?
<p>I have a dataframe that looks like the following</p> <pre><code>df city val 0 London 3 1 London -1 2 London -1 3 Paris -5 4 Paris -2 5 Rome 2 6 Rome 2 </code></pre> <p>I want to select only the city that have at least one <code>val &lt; 0</code>. I would like to have the foll...
<p>Create mask and filter rows with <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>:</p> <pre><code>df = df[df['val'].lt(1).groupby(df['city']).transform('any')] print (df) city va...
python|pandas
1
12,561
68,904,373
How to match 2 data frames if there is duplicates column name?
<p>From my previous question <a href="https://stackoverflow.com/questions/68892119/is-there-any-method-to-match-tabular-list-with-pivot-list-format">Is there any method to match tabular list with pivot list format?</a> , I have found the method to get the result by using DataFrames.melt method. However, I found my data...
<p>From your <code>DataFrames</code>, we build <code>df_full</code> :</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; df_full = pd.concat([pd.merge(df, df1, left_on='M', right_on='M_list_1'), pd.merge(df, df1, left_on='M', right_on='M_list_2')]).reset_index() &gt;&gt;&gt; df_fu...
python|pandas
2
12,562
69,248,661
Merging/Concat/Joining two dataframes
<p>i have a pandas dataframe with a distinct code identifier as detailed below:</p> <pre><code>df1 = pd.DataFrame([['a', 1], ['b', 2],['c', 3],['d', 4],['e', 5],['f', 5]], columns=['code', 'value1']) </code></pre> <p>with a second dataframe with the following</p> <pre><code>df2 = pd.DataFrame([['a', ...
<p>To only see the codes identified in df1 (i.e a-f) and have a third column entitled value2, you should use <code>merge</code> method with <code>how='inner'</code> and <code>on='code</code>:</p> <pre><code>&gt;&gt;&gt; df1.merge(df2, how='inner', on='code') code value1 value2 0 a 1 11 1 b 2 12 2 ...
python|pandas|join|merge|concatenation
0
12,563
61,142,519
Extract rows range with .between(), and specific columns, from Pandas DataFrame?
<p>I just got tripped on this: consider this example:</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df = pd.DataFrame({ "key":[1,3,6,10,15,21], "columnA":[10,20,30,40,50,60], "columnB":[100,200,300,400,500,600], "columnC":[110,202,330,404,550,606], }) &gt;&gt;&gt; df key columnA columnB c...
<p>You can just use the standard way of slicing DataFrames:</p> <pre><code>df[df['key'].between(2,16)][['key','columnA','columnC']] </code></pre>
python|pandas|dataframe
1
12,564
71,769,527
Correlation column between two column lists as a third column
<p>Assuming I have the following toy dataframe:</p> <pre><code>Firm goods products bear 0.1,0.2,0.3 0.4,1.5,9.7 ghost 2.1,3.7,1.5 6.2,2.3,5.5 </code></pre> <p>I can save each of the columns <code>goods</code> and <code>products</code> as numpy arrays by separating the numbers first.</p>...
<p>You need to loop here, you can use a list comprehension and <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html" rel="nofollow noreferrer"><code>scipy.stats.pearsonr</code></a>:</p> <pre><code>from scipy.stats import pearsonr df['corrcoef'] = [pearsonr(a,b)[0] for a,b in zip(df['g...
python|pandas
2
12,565
71,526,472
Does pandas categorical data speed up indexing?
<p>Somebody told me it is a good idea to convert identifying columns (e.g. person numbers) from strings to categorical. This would speed up some operations like searching, filtering and grouping.</p> <p>I understand that a 40 chars strings costs much more RAM and time to compare instead of a simple integer.</p> <p>But ...
<p><a href="https://pandas.pydata.org/docs/user_guide/categorical.html" rel="nofollow noreferrer">The user guide</a> has the following about categorical data use cases:</p> <blockquote> <p>The categorical data type is useful in the following cases:</p> <ul> <li><p>A string variable consisting of only a few different va...
pandas
1
12,566
69,847,155
Utilize TensorFlow Serving directly in a python process as a library
<p>I would like to run tensorflow serving without the HTTP or gRPC interfaces. In fact, I don't want it to even bind a port for receiving client requests. I'd like to leverage it as a library directly within my existing process, which is a python microservice. I know that it has a <a href="https://www.tensorflow.org/tf...
<p>We ended up simply running tensorflow-serving as a subprocess in a microservice app based on python/flask. We wrote up a blog post describing the implementation: <a href="https://medium.com/p/78d422d10c2c" rel="nofollow noreferrer">https://medium.com/p/78d422d10c2c</a></p>
tensorflow-serving
1
12,567
69,996,228
connect embedding layer with dimension (3,50) to lstm
<p>how to connect embedding layer with dimension (3,50) to lstm?</p> <p>array (3, 50) is fed to input &quot;layer_i_emb&quot; where three time steps with arrays of length 50 are stored in which product identifiers are stored</p> <p>I tried to connect it before reshape and it didn't work either. embedding adds dimension...
<p>The problem is that the <code>Embedding</code> layer is outputting a 3D tensor, but a <code>LSTM</code> layer needs a 2D input (excluding the batch dimension). Here are a couple options you can try:</p> <p><strong>Option 1</strong></p> <pre><code>import tensorflow as tf samples = 100 orders = 3 product_ids_per_orde...
python|tensorflow|keras|recurrent-neural-network|embedding
3
12,568
72,363,878
Aggregate overtimestamps in pandas e calculate mean
<p>I have a dataframe structured as well:</p> <pre><code>Timestamp Value 2021-06-07T03:19:49.000+0000 8 2021-06-07T03:20:19.000+0000 4 2021-06-07T03:20:49.000+0000 3 2021-06-08T03:11:05.000+0000 2 2021-06-08T03:11:35.000+0000 6 </code></pre> <p>The result I want is this, where I aggregate...
<p>Try <code>Series.Groupby</code></p> <pre><code>out = df.groupby(df.Timestamp.dt.date)['Value'].mean().reset_index() out Out[82]: Timestamp Value 0 2021-06-07 5.0 1 2021-06-08 4.0 </code></pre>
python|pandas|dataframe|timestamp
1
12,569
72,214,053
how to convert a lista of vectors into a numpy array to train a classifier in python?
<p>I have a pandas data frame that looks like this:</p> <pre><code> corpus tfidf labels 0 dfnkdfnkf asdfhedfh ajdladja [0.0, 0.0, 0.0, 0.01, 0.8] 60 1 dfnkdfnkf asdfhedfh ajdladja [0.0, 0.0, 0.0, 0.01, 0.8] 73 2 dfnkdfnkf asdfhedfh ajdladja [0.0, 0.0, 0.0...
<p>You can <code>explode</code> the lists from the <em>tfidf</em> column into multiple rows and then cast these values to a NumPy array, reshaping it appropriately:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np n_rows = df.shape[0] n_cols = len(df.loc[0, 'tfidf']) X = np.array(df['tfidf'].exp...
python|pandas|numpy|decision-tree|tf-idf
0
12,570
72,480,627
No matching distribution found for tensorflow-gpu==1.15.0
<p>I want to install this <code>requirements.txt</code>:</p> <pre><code>tensorflow-gpu==1.15.0 scipy==1.7.3 pillow==9.1.0 gdown ubuntu </code></pre> <p>my <code>python</code> version is:</p> <pre><code>Python 3.8.10 </code></pre> <p>my <code>pip3</code> version:</p> <pre><code>pip 20.0.2 </code></pre>
<p>Your problem is that this version of tensorflow is only available up to python version 3.7. As you can see <a href="https://pypi.org/project/tensorflow-gpu/1.15.0/" rel="nofollow noreferrer">here</a> under Programming Languages.</p>
python|tensorflow
0
12,571
50,552,449
Insert rows in pandas where one column misses some value in groupby
<p>Here's my dataframe:</p> <pre><code>user1 user2 cat quantity + other quantities ---------------------------------------------------- Alice Bob 0 .... Alice Bob 1 .... Alice Bob 2 .... Alice Carol 0 .... Alice Carol 2 .... </code></pre> <p>I want...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>set_index</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>reindex</code></a> by <a href="ht...
python|pandas
2
12,572
45,701,538
Replace zeros in one dataframe with values from another dataframe
<p>I have two dataframes df1 and df2: df1 is shown here:</p> <pre><code> age 0 42 1 52 2 36 3 24 4 73 </code></pre> <p>df2 is shown here:</p> <pre><code> age 0 0 1 0 2 1 3 0 4 0 </code></pre> <p>I want to replace all the zeros in df2 with their corresponding entries in df1. In more tech...
<p>You could use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.where.html" rel="nofollow noreferrer"><code>where</code></a>:</p> <pre><code>In [19]: df2.where(df2 != 0, df1) Out[19]: age 0 42 1 52 2 1 3 24 4 73 </code></pre> <p>Above, <code>df2 != 0</code> is a boolea...
python|pandas
9
12,573
45,404,345
Read in CSV trying to skip rows but having problems deleting first 6 rows
<p>I am trying to read in the following file, and am having problems reading in the csv. The CSV file contains a lot of information at the top of the file prior to the header of the data. I have tried skiprows, and content to skip the stuff at the top of the file but it is not working. </p> <p>Could someone offer a...
<p>You can use:</p> <pre><code>import requests from pandas.compat import StringIO dls = "http://www.spdrgoldshares.com/assets/dynamic/GLD/GLD_US_archive_EN.csv" r = requests.get(dls) daily_prices = pd.read_csv(StringIO(r.text), skiprows=6) </code></pre> <hr> <pre><code>print (daily_prices.head()) Date G...
python|pandas|csv|urllib|stringio
0
12,574
45,716,976
multiply two pandas dataframes
<p>I have two pandas dataframes:</p> <p>df1</p> <pre><code> id type NY PA MD 0 90 superurban 0.1 0.1 0.08 1 88 urban 0.1 0.08 0.08 2 75 suburban 0.06 0.04 0.04 3 60 rural 0.04 0.02 0.02 </code></pre> <p>df2</p> <pre><code> name item 0 NY 1000 1 PA 500 2 ...
<p>we can do it this way:</p> <pre><code>In [112]: d1[['NY','PA','MD']] *= d2.set_index('name')['item'] In [113]: d1 Out[113]: id type NY PA MD 0 90 superurban 100.0 50.0 20.0 1 88 urban 100.0 40.0 20.0 2 75 suburban 60.0 20.0 10.0 3 60 rural 40.0 10.0 5.0 </code...
python|pandas|dataframe
5
12,575
45,627,047
Fillna with most frequent if most frequent occurs else fillna with most frequent value of the entire column
<p>I have a panda dataframe </p> <pre><code> City State 0 Cambridge MA 1 NaN DC 2 Boston MA 3 Washignton DC 4 NaN MA 5 Tampa FL 6 Danvers MA 7 Miami FL 8 Cambridge MA 9 Miami FL 10 NaN FL 11 Washington DC <...
<p>IIUC:</p> <pre><code>def f(x): if x.count()&lt;=0: return np.nan return x.value_counts().index[0] df['City'] = df.groupby('State')['City'].transform(f) df['City'] = df['City'].fillna(df['City'].value_counts().idxmax()) </code></pre> <p>Output:</p> <pre><code> City State 0 Cambridge ...
python|pandas|dataframe
3
12,576
62,478,228
How do groups of IDs in rows of one pandas dataframe and use them to extract records from another dataframe
<p>I have two dataframes. One contains the contact information for individuals and households. The other contains an ID field for a Household, followed by the individuals in that household. I would like to select all records from the first dataframe and insert a column with their associated Household ID.</p> <p>Minimu...
<p>IIUC need <code>melt</code> then <code>merge</code></p> <p>If . <code>Type</code> isn't required you can ommit it from the 2nd line and merge clause.</p> <pre><code>s = pd.melt(df2,id_vars='Account_ID',var_name='Type',value_name='Constituent Id') s['Type'] = s['Type'].str.split('_',expand=True)[0] </code></pre> <...
python|pandas|dataframe
2
12,577
62,679,513
How to calculate statistical properties before and after specific cutoff point in pandas?
<p>I have a pandas dataframe that looks like this:</p> <pre><code>import pandas as pd dt = pd.DataFrame({'idx':[1,2,3,4,5,1,2,3,4,5], 'id':[1,1,1,1,1,2,2,2,2,2], 'value':[5,10,15,20,25, 55,65,75,85,97]}) </code></pre> <p>I have another that looks like this:</p> <pre><code>dt_idx = pd.DataFrame({'cutoff':[1,1,1,3,3,3,3,...
<p>A simple loop here is a good option. Get the cutoffs you care about using <code>value_counts</code> and then loop over those cutoffs. You can use <code>groupby</code> to get both the <code>&lt;=</code> and <code>&gt;</code> at the same time. Store everything in a dict, keyed by the cutoffs, and then you can <code>co...
python|python-3.x|pandas
2
12,578
62,887,293
How to adjust height of individual sublots in seaborn heatmap
<p>I have a heatmap using seaborn and am trying to adjust the height of the 4th plot below. You will see that it only has 2 rows of data vs the others that have more:</p> <p><a href="https://i.stack.imgur.com/eDhZJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eDhZJ.png" alt="" /></a></p> <p>I have...
<p>As normal, it is pretty funky/tedious with matplotlib. But here it is!</p> <pre><code>f = plt.figure(constrained_layout = True) specs = f.add_gridspec(ncols = 1, nrows = 4, height_ratios = [1,1,1,.5]) for spec, df in zip(specs, (df, df2, df3, df4)): ax = sns.heatmap(df,cbar=False,cmap=cmap, ax=f.add_subplot(spe...
python|pandas|matplotlib|seaborn
1
12,579
73,826,073
how to convert data of 536 files into excel having 536 columns using python
<p>I have 536 files in fasta format. each file has 5000 records. I have extracted all the records from the 536 files using python. Now I have to convert this data into excel so that each file name appears as a heading in the excel and each heading has its own records</p> <pre><code>import pandas as pd list1 = [10,20] l...
<p>Since you extracted the records already I assume you have the list of file names (here <code>files</code>) and the data (here combined in <code>record_list</code>) available.</p> <pre><code>files = ['file1', 'file2'] record_list = [[10, 20], [30, 40]] data_dict = {file: record for file, record in zip(files, record_...
python|excel|pandas
0
12,580
71,353,389
Is there a way to apply a function over all rows with the same values in a NumPy array?
<p>Let's say we have a matrix, A, that has the following values:</p> <pre class="lang-py prettyprint-override"><code>In [2]: A Out[2]: array([[1, 1, 3], [1, 1, 5], [1, 1, 7], [1, 2, 3], [1, 2, 9], [2, 1, 5], [2, 2, 1], [2, 2, 8], [2, 2, 3]]) </code></pre> <p>is t...
<p>A possible solution:</p> <pre><code>import numpy as np A = np.array([[1, 1, 3], [1, 1, 5], [1, 1, 7], [1, 2, 3], [1, 2, 9], [2, 1, 5], [2, 2, 1], [2, 2, 8], [2, 2, 3]]) uniquePairs = np.unique(A[:,:2], axis=0) output = np.empty((uniquePairs.shape[0], A.shape...
python|numpy|vectorization|numerical-integration
1
12,581
71,177,223
Correction of the recorded data in the CSV file after aggregation
<p>To aggregate the data, I use the code:</p> <pre><code>import pandas df = pandas.read_csv(&quot;./input_file.csv&quot;, delimiter=&quot;;&quot;, low_memory=False) df.head() count_severity = df.groupby(&quot;B&quot;)[&quot;A&quot;].unique() has_multiple_elements = count_severity.apply(lambda x: len(x)&gt;1) result = c...
<p>If you can use another format except csv, as lists are containers, pickle would be convenient in this case:</p> <pre><code>result.to_pickle(&quot;./output_file.csv&quot;) df2 = pd.read_pickle(&quot;./output_file.csv&quot;) </code></pre>
python|python-3.x|pandas
0
12,582
71,278,585
how to get valid latitude and longitude from linestring
<p>I want a list of latitudes and longitudes of North Carolina roads for my research work. So I got the .shp file from here <a href="https://xfer.services.ncdot.gov/gisdot/DistDOTData/NCRoutes_SHP.zip" rel="nofollow noreferrer">https://xfer.services.ncdot.gov/gisdot/DistDOTData/NCRoutes_SHP.zip</a></p> <p>and I loaded ...
<p>You need to <a href="https://geopandas.org/en/stable/docs/reference/api/geopandas.GeoDataFrame.to_crs.html" rel="nofollow noreferrer">transform your geometries to a geographic coordinate system.</a>. Let's use the poplar WGS 84. But first of all, let's check to see that the data has a CRS defined. Printing the <cod...
geopandas|shapefile|multilinestring
0
12,583
52,004,984
Find the most frequent string in a Data frame
<p>I am new to Python programming.I have a pandas data frame in which two string columns are present.</p> <p>Data frame is like below:</p> <pre><code>Case Action Create Create New Account Create New Account Create New Account Create New Account Create Old Account Delete Del...
<p>Using <code>crosstab</code> before <code>groupby</code> <code>tail</code></p> <pre><code>pd.crosstab(df.Case,df.Action,normalize='index').stack().sort_values().groupby(level=0).tail(1) Out[769]: Case Action Delete DeleteOldAccount 0.6 Create CreateNewAccount 0.8 dtype: float64 </code></pre> <...
python|string|pandas|nlp
1
12,584
52,061,708
Pandas data frame. Column consistency. Bring integer values to fixed length
<p>I open the .tsv file in a following way:</p> <pre><code>cols = ['movie id','movie title','genre'] movies = pd.read_csv('movies.dat', sep='::', index_col=False, names=cols, encoding="UTF-8",) +---+----------+-------------------------------------+ | | movie id | movie title | +---+---------...
<p>I will recommend convert to <code>str</code> , then format with <code>pad</code> or <code>rjust</code> </p> <pre><code>s.astype(str).str.rjust(7,'0') Out[168]: 0 0000008 1 0000012 2 0000091 3 0000417 dtype: object </code></pre>
python|pandas|csv|dataframe
1
12,585
72,543,156
Pandas - Grab value x from column a if column y contains b
<p>Hi there stack overflow community,</p> <p>I'm trying to get a tree-hierarchy from the following dataframe:</p> <pre><code> SP VP 0 -- king 1 king knight 1 2 king knight 2 3 knight 1 knight 3 </code></pre> <p>In column 'SP' I've the superior and in 'VP' the...
<p>excuse my English, with subordinate do you mean that the SP and VP columns belong to the same index?</p> <p>If you want only certain rows to belong to the same index and others not, this is not possible. It must be the totalities of the columns that belong to the index.</p> <p>For what purpose do you want them to be...
python|pandas|tree
0
12,586
72,554,976
Regex find keyword followed by N characters
<p>I have a df column with URL having keyword with hash values, example</p> <pre><code>/someurl/env40d929fadbe746ecagjbf6c515d30686/end /some/other/url/envlabel40d929fadbe746ecagjbf6c517t30686/envvar40d929fadbe746ecagjbf6c515d306r6 </code></pre> <p>Goal is to replace words <code>env.following.32.char.hash</code> into <...
<p>You can use the regex <code>'(env(label|var)?)\w{32}'</code> which simply captures <code>env</code> and <code>label</code> if it is present. ie <code>?</code> ensures that <code>label</code> is captured if present. Replace the matched string with the first captured group. ie <code>\\1</code> within the curly braces....
python|regex|pandas
2
12,587
72,673,045
Relative distance to previous row, in pandas/python
<p>I have a dataframe with a series of locations in it. The three columns i have so far are:</p> <pre><code>['Location number','x_coordinate', 'y_coordinate] </code></pre> <p>Now i would like to have a forth column which indicates the distance. between te previous one.</p> <p>As the firts location does not has a preced...
<p>The <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.diff.html" rel="nofollow noreferrer"><code>pd.Series.diff</code></a> method should do the trick:</p> <pre class="lang-py prettyprint-override"><code>df['manhattan_distance'] = ( df.x_coordinate.diff().fillna(0).abs() + df.y_coordinate.di...
python|pandas|geolocation
1
12,588
72,610,356
Multilabel text classification using BERT and Tensorflow 2
<p>I am trying to build a simple multilabel text classification pipeline using BERT; the goal is to classify the content of social media posts and any post can have more than one label (i.e., a post can be labeled both &quot;Medications&quot; and &quot;Physical and Mental Health&quot;). I am very new to BERT and was tr...
<p>You can avoid this error by selecting <strong>Tensorflow version 1.x</strong> before your code:</p> <pre><code>%tensorflow_version 1.x import tensorflow as tf tf.__version__ # to check the tensorflow version </code></pre> <p>Output:</p> <pre><code>TensorFlow 1.x selected. '1.15.2' </code></pre> <p>This code line...
python|tensorflow|text-classification|bert-language-model|multilabel-classification
0
12,589
72,685,216
Has anyone implemented a optuna Hyperparameter optimization for a Pytorch LSTM?
<p>I am trying to implemented a Optuna Hyperparameter optimization for a Pytorch LSTM. But I do not know how to define my model correctly. When I just use <code>nn.linear</code> erverything works fine but when I use <code>nn.LSTMCell</code> I get the following error:</p> <pre><code>AttributeError: 'tuple' object has n...
<p>I implemented a solution by my self. I am not sure if it's the most pythonic but it works. Suggestions for improvement are welcome.</p> <pre><code>def train_and_evaluate(param, model, trail): # Load Data train_dataloader = torch.utils.data.DataLoader(Train_Dataset, batch_size=batch_size) Test_datalo...
python|pytorch|lstm|optuna
0
12,590
59,786,528
Why is there unnecessary whitespace while plotting figures with pandas, matplotlib and seaborn?
<p>Whenever I plot figures using matplotlib or seaborn, there is always some whitespace remaining at the sides of the plot and the top and bottom of the plot. The (x_0,y_0) is not in the bottom left corner, x_0 is offset a little bit to the right and y_0 is offset a little bit upwards for some reason? I will demonstrat...
<p>The "whitespace" is caused by the <a href="https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.margins.html?highlight=margins#matplotlib.axes.Axes.margins" rel="nofollow noreferrer">plot <em>margins</em></a>. A better way to get rid of them without changing the axes limits explicitly is to set 0-margins</p> <pr...
python-3.x|pandas|matplotlib|seaborn
4
12,591
59,590,085
how do I mask the input of lstm in tf.keras
<p>I am building a hybrid model (RNN on top of CNN) and I want to mask the input, the problem is<br> that mask_zero is not supported by conv layers. I have tried to do masking and pass it to lstm like this: </p> <pre><code>inputs = tf.keras.layers.Input(shape=(100,)) mask = tf.keras.layers.Masking().compute_mas...
<p>Have you tried checking the Docs for <code>Tensorflow</code>? Go to this <a href="https://www.tensorflow.org/guide/keras/masking_and_padding" rel="nofollow noreferrer">link</a> I think it will help you.<br> In the above example, they add <code>mask_zero=True</code></p> <pre><code>embedding = layers.Embedding(input_...
python|tensorflow|keras
1
12,592
59,802,855
Pivot_table from lists in a column value
<p>I have a dataframe like:</p> <pre><code> ID Sim Items 1 0.345 [7,7] 2 0.604 [2,7,3,8,5] 3 0.082 [9,1,9,1] </code></pre> <p>I want to form a <code>pivot_table</code> by:</p> <pre><code>df.pivot_table(index ="ID" , columns =...
<p>Use explode(<em>new in pandas 0.25+</em>) before pivot;</p> <pre><code>df.explode('Items').pivot_table(index ="ID" , columns = "Items", values="Sim") </code></pre> <hr> <pre><code>Items 1 2 3 5 7 8 9 ID 1 NaN NaN N...
python|pandas|dataframe|pivot-table
2
12,593
58,040,556
'ValueError: could not convert string to float' in python sklearn
<p>I have a Pandas DataFrame with date columns. The data is imported from a csv file. When I try to fit the regression model, I get the error <code>ValueError: could not convert string to float: '2019-08-30 07:51:21</code>. .</p> <p>How can I get rid of it?</p> <p>Here is dataframe.</p> <p><strong>source.csv</strong...
<p>Try a thing like this, after reading the model</p> <pre><code>import datetime to_timestamp_fct = lambda x: datetime.datetime.strptime(x, '%Y-%m-%d %H:%M:%S').timestamp() model['rssi_ts'] = model['rssi_ts'].apply(to_timestamp_fct) </code></pre>
python|pandas|numpy|scikit-learn|random-forest
0
12,594
57,978,510
How do I reshape this tensor?
<p>I have a <code>torch.tensor</code> that looks like this:</p> <pre><code>tensor([[[A,B,C], [D,E,F], [G,H,I]], [[J,K,L], [M,N,O], [P,Q,R]]] </code></pre> <p>I want to reshape this tensor so that its dimensions are <code>(18, 1)</code>. I want the new tensor to look like t...
<pre class="lang-py prettyprint-override"><code>a = torch.arange(18).view(2,3,3) print(a) #tensor([[[ 0, 1, 2], # [ 3, 4, 5], # [ 6, 7, 8]], # # [[ 9, 10, 11], # [12, 13, 14], # [15, 16, 17]]]) aa = a.permute(1,2,0).flatten() print(aa) #tensor([ 0, 9, 1, 10, 2, 11, 3,...
python|pytorch
4
12,595
55,070,717
Outer join within a Pandas table
<p>I have a PANDAS dataframe with three string columns that looks something like this:</p> <pre><code>Name Surname MiddleName James Bond A Maggie Sweenie B </code></pre> <p>I want to create a kind of outer join within the table so that every possible combination of Name, Surname and MiddleName is...
<p>IIUC using <code>product</code></p> <pre><code>import itertools yourdf=pd.DataFrame(list(itertools.product(*df.values.T.tolist())),columns=df.columns) yourdf Out[937]: Name Surname MiddleName 0 James Bond A 1 James Bond B 2 James Sweenie A 3 James Sweenie ...
python|pandas
4
12,596
49,619,995
How to control when to compute evaluation vs training using the Estimator API of tensorflow?
<p>As stated in <a href="https://stackoverflow.com/questions/45952149/tensorflow-estimator-periodic-evaluation-on-eval-dataset">this question</a>:</p> <blockquote> <p>The tensorflow documentation does not provide any example of how to perform a periodic evaluation of the model on an evaluation set</p> </blockquote> ...
<p>From my understanding, evaluation happens using a respawned model from the latest checkpoint. In your case, you don't save a checkpoint until 2000 steps. You also indicate <code>max_steps=125</code>, which will take precedence over the data set you feed your model.</p> <p>Therefore, even though you indicate batch s...
python|tensorflow
4
12,597
49,778,594
Numpy automatic elementwise function
<p>I have a question regarding numpy. </p> <p>Let's assume I have a function </p> <pre><code>def calcSomething(A,t): return t*A </code></pre> <p>I want to pass A a constant numpy-array, e.g. <code>A=np.array([1.0,2.0])</code> and t as equidistant points, e.g. <code>t = np.linspace(0.0,1.0,10)</code>. Now, when ...
<p>Where possible, using numpy functions and operators that operate on the whole arrays, and do the necessary <code>broadcasting</code> for you:</p> <pre><code>In [24]: A = np.array([1.0,2.0]); t = np.linspace(0.0, 1.0, 10) In [25]: x = t[:,None] * A[None,:] In [26]: x.shape Out[26]: (10, 2) In [27]: x[:3,:] Out[27]: ...
python|numpy|elementwise-operations
1
12,598
73,327,900
Pandas DF - Efficient way to loop through DF to find minimum values of one column from rows with common values in another column
<p>I have a dataframe that looks something like:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>matter</th> <th>work_date</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>01/01/2020</td> </tr> <tr> <td>2</td> <td>01/02/2020</td> </tr> <tr> <td>1</td> <td>01/04/2020</td> </tr> <tr> <td>2</td...
<p><code>transform</code> does what you want and should be fast</p> <p>The steps are (1) group the rows together that have the same <code>matter</code> (2) for each group calculate the minimum <code>work_date</code> and (3) save these values as a new column.</p> <pre><code>import pandas as pd import io df = pd.read_cs...
python|pandas|dataframe
1
12,599
73,436,059
VlookUp in python and select certain columns
<p>I want to perform vlookup on two excel files, and select only certain column in second excel file</p> <p>Here's Book1.xlsx</p> <pre class="lang-none prettyprint-override"><code>BILL_ID APPROVED_BY BILL_DESCRIPTION BILLED_AMOUNT BILL_CONTROL_NUMBER 163191467 111 Loan Repayment 6792731.25 ...
<p>Change the line</p> <p><code>inner_join = pd.merge(df1,df2,left_on='BILL_CONTROL_NUMBER',right_on='Control_number')</code></p> <p>to this</p> <p><code>inner_join = pd.merge(df1,df2[['Name','Control_number']],left_on='BILL_CONTROL_NUMBER',right_on='Control_number')</code></p> <p>You can specify columns you want using...
python|pandas|vlookup
0