Unnamed: 0
int64
0
378k
id
int64
49.9k
73.8M
title
stringlengths
15
150
question
stringlengths
37
64.2k
answer
stringlengths
37
44.1k
tags
stringlengths
5
106
score
int64
-10
5.87k
368,200
73,680,220
Split and explode a string with different amount of arrays of a pandas dataframe to separate rows
<p>I try to split a column of text strings which contains comma-separated values (Genres by Song). For further analysis I need every value of the string in a new row. I am new to python. Managed to import the excel in a pandas dataframe. Couldn't find an example of my problem on stack.</p> <p>df:</p> <div class="s-tabl...
<p>Perfect job for <code>explode</code>:</p> <pre class="lang-py prettyprint-override"><code>df[&quot;Genres&quot;] = df[&quot;Genres&quot;].apply(lambda g: g.split(&quot;,&quot;)) df = df.explode(&quot;Genres&quot;) # To avoid surprise down the road, remove # leading and trailing spaces with strip df[&quot;Genres&quo...
python|pandas
1
368,201
73,548,564
Leveraging for loop to run slices of dataframe through supervised model based on one column value
<p>I have the following dataframe and would like to group the data by <code>cluster</code> number to generate 5 new dataframes (the clusters go from 0-4), and then further split them up into training and test sets based on the <code>Date</code> column and run each train/test dataframe through a Random Forest regressor....
<p>A for loop is perfect here!</p> <pre><code>columns = whatever_df.columns.tolist() cols = [c for c in columns if c not in ['Date', 'CPR']] from sklearn.ensemble import RandomForestRegressor for i in range(5): cluster = whatever_df[whatever_df['cluster'] == i] train = cluster[cluster['Date'] &lt;= max(cluste...
python|pandas|random-forest|train-test-split|hardcode
1
368,202
73,612,209
Pandas - performing aggregation based on list of columns in dictionary
<p>I want to perform a loop to sum (column: want) based on a list of columns stored as a dictionary. The loop outputs uses the underlying dataset d1 and performs a pivot operation and then outputs multiple datasets d_new1 and d_other1 based on the columns specified in the loop (dictionary). I am having troubles referen...
<p>The answer was right in front of me. I just had to rearrange and simplify this code.</p> <pre><code>import pandas as pd d1 = pd.DataFrame({'col1': [1, 2], 'col3': [3, 4],'col4': [3, 4], 'something2': [1, 2], 'something3': [3, 4], 'something4': [3, 4]}) for key, value in {'new1':[['col1'],{'col3':'mean','col4':'mean...
python|pandas|dictionary|pivot-table
0
368,203
73,697,974
remove from , and transfer to next cell in pandas
<p>remove from , and transfer to next cell in pandas for eg,</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>city</th> <th>country</th> </tr> </thead> <tbody> <tr> <td>Toronto,Canada</td> <td>N/A</td> </tr> </tbody> </table> </div> <p>output:</p> <div class="s-table-container"> <table class...
<p>If need replace missing value in <code>country</code> column by last value after split <code>city</code> by <code>,</code> use:</p> <pre><code>df['country'] = df['country'].fillna(df['city'].str.split(',').str[-1]) </code></pre> <p>Or if need assign all column in <code>country</code> column:</p> <pre><code>df['count...
python|excel|pandas
1
368,204
73,649,586
how to convert ML Project from a GPU project to CPU project?
<p>I am learning ML and i want to re train a AI model for lane detection.</p> <p>I want to be familiar with the ML training process. The accuracy/result is not my primary goal and i do not need a best ML model for lane detection.</p> <p>I found this <a href="https://github.com/Turoad/CLRNet" rel="nofollow noreferrer">A...
<p>you can use the <code>tensor.to(device)</code> command to move a tensor to a device.</p> <p>The <code>.to()</code> command is also used to move a whole model to a device, like in the post you linked to.</p> <p>Another possibility is to set the device of a tensor during creation using the device= keyword argument, li...
pytorch
0
368,205
73,623,732
Pandas dataframe delete duplicate base date column
<p>I have 2 datafames with same columns that one of the column is date.</p> <p>I try to concat the dataframes and delete the row with the earlier date, when the primary keys are same.</p> <p>Input (df1 &amp; df2):</p> <pre><code>pk1 | pk2 | C | DATE 1 | 2 | 3 | 05-09-22 2 | 3 | 4 | 05-09-22 pk1 | pk...
<p>You need to drop_duplicates while keeping the first.</p> <pre><code>df = pd.concat([df1,df2]) # concating df.sort_values(by=['DATE'], ascending=True, inplace=True) # sorting by date df = df.drop_duplicates(subset=['pk1', pk2], keep='first') # dropping duplicates </code></pre>
python|pandas
1
368,206
73,611,858
How to allow sign difference of any column in a comparison of two matrices, Python3?
<p>I have two numpy 3d arrays with dimension of <code>m-n-n</code>: <code>arr1</code> and <code>arr2</code>. Each inner array is a square matrix (<code>n-n</code>). In my unittest work, <code>arr1</code> and <code>arr2</code> should be the same, except that any column in any inner matrix in <code>arr1</code> can have a...
<pre class="lang-py prettyprint-override"><code>is_diff_signs = ((np.sign(arr1) * np.sign(arr2)) == -1).all(axis=1, keepdims=True) real_total = arr1 + arr2 ideal_total = np.where(is_diff_signs, 0, real_total) np.testing.assert_almost_equal(real_total, ideal_total) </code></pre> <p>If two arrays are equal except ...
python-3.x|numpy
2
368,207
73,711,201
How to build and customize an XML tree from a dataframe?
<p>I have a DataFrame on the following format which I want to transform to XML</p> <pre><code>Parameter Name | Value | Comment lev1.lev12 5 &quot;Comment 1&quot; lev1.lev13.lev14 10 &quot;Comment 2&quot; lev2.lev22 &quot;hi&quot; &quot;Comment 3&quot; lev2.lev23 NaN ...
<p>With the dataframe you provided:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd df = pd.DataFrame( { &quot;Parameter Name&quot;: [ &quot;lev1.lev12&quot;, &quot;lev1.lev13.lev14&quot;, &quot;lev2.lev22&quot;, &qu...
python|pandas|xml|elementtree
1
368,208
73,744,523
Plotting stacked bar chart
<p>I'm trying to create a stacked bar chart, with <code>xaxis = 'customer_id(count)</code>, <code>yaxis = 'age_band'</code>, and the 3 different loyalty groups stacked in the chart (hue), so I should see 6 bars each with 2-3 different colours.</p> <p>code I've tried:</p> <pre class="lang-py prettyprint-override"><code>...
<p>IIUC use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot_table.html" rel="nofollow noreferrer"><code>DataFrame.pivot_table</code></a>:</p> <pre><code>(df.pivot_table(index='age_band',columns='loyalty', values='customer_id', aggfunc='nunique') .plot(kind='bar', stacked...
python|pandas|matplotlib|bar-chart
2
368,209
73,577,631
How to Convert the Numpy array to a DataFrame?
<p>I have to convert this numpy array to a dataframe</p> <pre><code>array([[['ID 0x4501'], ['Delivery_person_ID S13DEL02'], ['Delivery_person_Age 21.0000'], ..., ['City Urban'], ...
<p>Can be done like this:</p> <pre><code>data = {} for item in my_array.ravel(): if 'dtype: object' in item: continue parts = item.split() key = ' '.join(parts[:-1]) value = parts[-1] try: data[key].append(value) except KeyError: data[key] = [value] df = pd.DataFrame(da...
python|pandas|dataframe|numpy
0
368,210
73,719,753
What would be the fastest way to append newly reshaped image matrix to new array?
<pre><code>last_conv_w, last_conv_h, n_channels = last_conv_output.shape upscaled_h = last_conv_h * height_factor upscaled_w = last_conv_w * width_factor upsampled_last_conv_output = np.zeros((upscaled_h, upscaled_w, n_channels)) for x in range(0, n_channels, 512): upsampled_last_conv_output[:, :, x:x+512] = cv2....
<p>You could accumulate the arrays in a list</p> <pre><code>alist = [] for x in range(0, n_channels, 512): alist.append( cv2.resize(last_conv_output[:, :, x:x+512], (upscaled_w, upscaled_h), cv2.INTER_CUBIC)) upsampled_last_conv_output = np.concatenate(alist, axis=2) </code></pre> <p>I haven't tested this; I'm just...
python|numpy|opencv
0
368,211
73,811,880
Merge every N dataframes in a list
<p>I have a list with dataframes. I want to merge every 6 dataframes. The way I m doing it is very manual, so I am doing:</p> <pre><code>from functools import reduce import paandas as pd list1 = bigList[0:5] list1DF = reduce(lambda df1,df2: pd.merge(df1,df2,on='index', how = 'outer'), list1) list2 = bigList[6:11] lis...
<p>Sure – just grab chunks of your big list with a step of <code>5</code> and apply what you've been doing anyway:</p> <pre><code>from functools import reduce big_list = ... smaller_list = [] for idx in range(0, len(big_list), 5): chunk = big_list[idx:idx + 5] combined_df = reduce(lambda df1, df2: pd.merge(df...
python|python-3.x|pandas|merge
2
368,212
73,734,634
create sub-directories and files from pandas dataframe
<p>Having this dataframe at hand:</p> <pre class="lang-py prettyprint-override"><code>data = {'user': [7, 7, 7, 7, 7, 7, 7, 11, 11, 11], 'session_id': [15, 15, 15, 15, 31, 31, 31, 43, 43, 43], 'logtime': ['2016-04-13 07:58:40','2016-04-13 07:58:41','2016-04-13 07:58:42', '2016-04-13 07:58:43','2016-04-01 ...
<p>This could be done with <code>os.makedirs</code> and <code>groupby</code>:</p> <pre><code>import os # make the data folder if needed, change the path if needed base_folder = '/Data' os.makedirs(base_folder, exist_ok=True) for (user_id,sess_id), data in df.groupby(['user', 'session_id']): user_folder = f'{base_...
python|pandas|dataframe
4
368,213
73,628,796
Pandas apply custom function to each dataframe row and append results
<p>How can I apply a custom function to each row of a Pandas dataframe <code>df1</code>, where:</p> <ol> <li>the function uses values from a column in <code>df1</code></li> <li>the function uses values from another dataframe <code>df2</code></li> <li>the results are appended to <code>df1</code> column-wise</li> </ol> <...
<p>You can do</p> <pre><code>df1 = df1.join(df1.apply(lambda x : myfunc(df2, x['x']),axis=1)) Out[152]: x 0 1 2 3 0 1 100 200 300 400 1 2 200 400 600 800 2 3 300 600 900 1200 </code></pre>
python|pandas
2
368,214
73,584,345
How to export all of the gathered data to .CSV?
<p>At the moment running this code will make just a single .csv file with only the last result included. How can I export all the fetched data to one .csv file?</p> <pre><code>import requests import pandas as pd import json from pandas.io.json import json_normalize from bs4 import BeautifulSoup for id in range (1,...
<p>At the moment you're only saving the last iteration of your loop. The key is to define a data structure outside of the loop and add to it with each iteration. For example, you could define a dataframe and add to it using <a href="https://pandas.pydata.org/docs/reference/api/pandas.concat.html" rel="nofollow noreferr...
python|pandas|csv|web-scraping|beautifulsoup
0
368,215
73,599,146
How to get average between first row and current row per each group in data frame?
<p>i have data frame like this,</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">id</th> <th style="text-align: center;">value</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">a</td> <td style="text-align: center;">2</td> </tr> <tr> <td style="text-ali...
<p>You can group the dataframe by <code>id</code>, then calculate the expanding mean for <code>value</code> column for each groups, then shift the expanding mean and get it back to the original dataframe, once you have it, you just need to <code>ffill</code> on <code>axis=1</code> on for the <code>value</code> and <cod...
python|pandas|mean
4
368,216
73,604,506
Assign values of a list to cell of dataframe using .loc in a pandas dataframe
<p>I have a dataframe <code>df</code> like below :</p> <pre><code>data = {'A': [1, 2, 3, 4, 5, 6], 'B':[1, 0, 0, 0, 0, 0]} df = pd.DataFrame(data) df | A | B | +-----+----+ | 1 | 1 | | 2 | 0 | | 3 | 0 | | 4 | 0 | ...
<p>This works for me:</p> <pre><code>list_values = pd.DataFrame(['A', 'B', 'C']) new_df = pd.concat([df, list_values], axis=1) new_df.columns = ['A', 'B', 'list_values'] # Naming the columns here new_df </code></pre> <p>The output:</p> <pre><code> A B list_values 0 1 1 A 1 2 0 B 2 3 0 C 3 4 ...
python-3.x|pandas|dataframe
1
368,217
73,528,312
Create new column and assign values from 1 to 100 based on percentiles
<p>I am very new to <code>pandas</code> and Python in general.<br /> I have a dataframe with many columns, one of them is <code>score_init</code> (may contain duplicate values):</p> <pre><code>+----------+ |score_init| +----------+ | 38.27| | 39.27| | 29.16| | 32.60| | 40.45| | 19.49| | 48.2...
<p>Use <a href="https://pandas.pydata.org/docs/reference/api/pandas.qcut.html" rel="nofollow noreferrer"><code>qcut</code></a>:</p> <pre><code>df['scores_new'] = 100 - pd.qcut(df['score_init'], 100).cat.codes </code></pre> <p>output:</p> <pre><code> score_init scores_new 0 38.27 34 1 39.27 ...
python|pandas
1
368,218
73,531,189
Python Pandas: Counting the amount of subsequent value and assign a name if conditions are met
<p>For example I have created this data frame:</p> <pre><code>import pandas as pd df = pd.DataFrame({'Cycle': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,...
<p>Start by counting the number of rows in each group with <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>pandas.DataFrame.groupby</code></a>, <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.transform.html" rel="nofollow norefe...
python|pandas|dataframe|count
3
368,219
73,613,455
None of [Index([], dtype='object')] are in the [columns] - pd.merge error
<p>I am having problems when Im trying to merge two dataframes. Here is an example of dataframe structures.</p> <p>DataFrame 1:</p> <pre><code>code name 1 billy 2 gary 3 fred </code></pre> <p>DataFrame 2:</p> <pre><code>code valeu date 1 2 05/25 2 3 06/26 5 4 07/27 </code></pre> <p>I...
<pre><code>import pandas as pd df1 = pd.DataFrame([ [1, 'billy'], [2, 'gary'], [3, 'fred'] ], columns=['code', 'name']) df2 = pd.DataFrame([ [1, 2, '05/25'], [2, 3, '06/26'], [5, 4, '07/27'] ], columns=['code', 'valeu', 'date']) df3 = df2.merge(df1, how='left', on='code') print(df3) </code></pre> <p>...
python|pandas|dataframe
0
368,220
73,740,979
Unable to read csv file in jupyter notebook
<p>I was trying to read csv file in jupyter notebook but it showed error of filenotfound. Then I tried to check whether my file is present then it shoewd false as output. But I have checked the file location in my files explorer and the csv file is present .How should I read the file?</p> <pre><code>import os os.path.i...
<p>maybe try:</p> <pre><code>import pandas as pd df = pd.read_csv('your-filepath') </code></pre> <p>you could also try to move the file into your project directory so that it is in the same folder as the .ipynb</p>
pandas|jupyter-notebook|operating-system|opencsv|read.csv
0
368,221
73,825,845
I want to convert (01-07-57) to date value
<p><img src="https://i.stack.imgur.com/HwSzj.png" alt="enter image description here" /></p> <p>I want to convert the datum column which is a string to <code>DateTime</code> format.</p> <p>when I use</p> <pre><code>sf['Datum'] = pd.to_datetime(sf['Datum']).dt.date </code></pre> <p>its showing the year as 2057 instead of...
<p>There's a answer over here: <a href="https://stackoverflow.com/questions/37766353/pandas-to-datetime-parsing-wrong-year">pandas to_datetime parsing wrong year</a></p> <p>It's due to 2 digit years from 0-68 mapping to 20xx.</p>
python|python-3.x|pandas
0
368,222
73,780,981
How to get the group name and index list in a grouped pyspark dataframe?
<p>I want the equivalent of this pandas code in pyspark. The following pandas code generates the atable names and the indexes where the atable name is found:</p> <pre><code>import pandas as pd df1 = pd.DataFrame({ 'atable': ['Users', 'Users', 'Domains', 'Domains', 'Locks'], 'column': ['col_1', 'col_2',...
<p>As already pointed out by samkart there is no intrinsic order in a Spark dataframe. If you want to retain the information which row in the original dataframe went into which group during the grouping operation, you can use <a href="https://spark.apache.org/docs/3.1.3/api/python/reference/api/pyspark.sql.functions.mo...
pandas|apache-spark|pyspark
1
368,223
73,558,582
Format DataFrame to Achieve Equal Number of Digits in Each Column
<p>I would like to format the DataFrame</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Col1</th> <th>Col2</th> <th>Col3</th> </tr> </thead> <tbody> <tr> <td>-0.012</td> <td>3.2</td> <td>nan</td> </tr> <tr> <td>0</td> <td>-1</td> <td>15.2</td> </tr> <tr> <td>0.5</td> <td>7.53</td> <td>76.88...
<pre><code>df.applymap(float) </code></pre> <pre><code> Col1 Col2 Col3 1 -0.012 3.20 NaN 2 0.000 -1.00 15.20 3 0.500 7.53 76.88 </code></pre> <p>data use</p> <pre><code>data={'Col1': {1: '-0.012 ', 2: '0', 3: '0.5'}, 'Col2': {1: '3.2', 2: '-1', 3: '7.53'}, 'Col3': {1: np.nan, 2: '15.2',...
python|pandas|dataframe|format|trailing
0
368,224
73,784,205
Python - NumPy array splitting in particuler indices
<p>I have a binary file containing multiple UDP packets received from a server. Each UDP packet starts with 0xAAAA and ends with 0xD6D6 (start marker and end marker). I read the file and store it in a NumPy array. Now I have to split that into multiple smaller arrays corresponding to individual packets.</p> <p>I tried ...
<p>I think you'll have to use a for-loop since the size of each packet is not guaranteed to be the same size:</p> <pre><code>packets_data = np.array() # This should be your packets array of shape(data_length,) individual_packets = [] one_packet = [] for data in packets_data: one_packet.append(data) if data ==...
python|numpy
0
368,225
73,711,299
how the code '-input[range(target.shape[0]),target]' works?
<p>I'm learing pytorch.Reading the official tutorial,I met the preplexing code. input is a tensor, so is target.</p> <pre><code>def nll(input,target): return -input[range(target.shape[0]),target].mean() </code></pre> <p>And the pred is:<br /> <img src="https://i.stack.imgur.com/uxVGb.png" alt="pred" /></p> <p>targ...
<p>The code <code>input[range(target.shape[0]), target]</code> simply picks, from each row <code>i</code> of <code>input</code> the element at column indicated by the corresponding element of <code>target</code>, that is <code>target[i]</code>.<br /> In other words, if <code>out = input[range(target.shape[0]), target]<...
python|pytorch
2
368,226
73,720,557
bar chart in python grouped by the sex column
<p>I have a data frame that looks something like this and I want am trying to make two grouped bar charts where one is grouped by sex and it shows the counts for the disease for males and females:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">Age</th> <th style="...
<p><strong>Chart:</strong></p> <p><a href="https://i.stack.imgur.com/e57jS.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e57jS.jpg" alt="enter image description here" /></a></p> <p><strong>Code:</strong></p> <pre><code>import pandas as pd import matplotlib.pyplot as plt d = {'Age': [23, 43, 32, 51...
python|pandas
2
368,227
73,618,115
How to find the pseudo-inverse of a large sparse matrix?
<p>I have to invert a large sparse matrix (50000 x 12000). It was initially stored as <code>numpy.ndarray</code> and the size of the matrix was around 3.5 GB. I have tried inverting this matrix using <code>numpy.linalg.pinv</code> but it crashes the jupyter notebook kernel. Converting this <code>numpy.ndarray</code> to...
<p>The inverse or pseudoinverse of a sparse matrix is not necessarily sparse, so you'd have to store a full matrix of a similar size anyway when computing <code>pinv</code> along with multiple intermediate steps. Do you really absolutely need the pseudoinverse explicitly?</p> <p>We can solve systems also via e.g. <a hr...
python|numpy|matrix|scipy|sparse-matrix
2
368,228
73,528,506
Numpy Array non-sequentially divide the columns of the main array into n sub-arrays
<p>I've been trying to do something like a <em>numpy.array_split()</em>, but to split it like this instead:</p> <p><a href="https://i.stack.imgur.com/kQ8AJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kQ8AJ.png" alt="enter image description here" /></a> So It would return an array (for example let...
<p>Not sure if a native solution exists but you can use:</p> <pre><code># get groups group = np.arange(a.shape[1])%n # groups sorting order order = np.argsort(group) # get counts of each group (in order as the output is sorted) _, idx = np.unique(group, return_counts=True) # split the reindexed array out = np.split(a[:...
python|arrays|numpy|split
3
368,229
73,532,569
Shift rows with missing NaN's to it's own column
<p>I am parsing a lot of netstat data and the way I have been handling my solution now is by just removing the row and referencing manually. If I see proto is NaN, I just parse the row completely. But I am unable to append the row and the rest of the dataframe due to mismatched sizing.</p> <p>I was wondering if it woul...
<p>Try this:</p> <p>You said it is always in the next row, so we just need to get a Series of <code>Proto</code> which only contains the values of the rows with <code>NaN</code>. Then we just shift it by 1 and create a new column with it.</p> <pre class="lang-py prettyprint-override"><code>cols = ['LocalAddress', 'Fore...
python|pandas|dataframe
2
368,230
73,638,077
Replace function only works on strings and not substrings
<p>I have a dataframe with multiple columns and rows. I'm trying to replace commas with dots in all strings in the dataframe, e.g. I want to change value 'John, Doe' to 'John. Doe'</p> <p>I'm using the following line:</p> <pre><code>df_fulfill = df_fulfill.replace(',','.') </code></pre> <p>However, this line only repla...
<p>I was missing regex=True in replace. The following line worked:</p> <pre><code>df_fulfill = df_fulfill.replace(',','.', regex=True) </code></pre>
python|pandas|dataframe|replace
0
368,231
73,819,974
Fill NaNs in rows with duplicated field based on another field value
<p>I have the following table:\</p> <pre><code>Name | ID | Azimut\ foo | 1 | 180\ foo | 6 | NaN\ bar | 1 | NaN\ bar | 6 | 200 </code></pre> <p>I want to search for duplicates that have IDs with the value of 1 or 6 (the table can have other numbers) and if the &quot;Azimut&quot; value is NaN, co...
<p>IIUC you want to fill null values per <code>name</code> with other non-null value in that group. Then try:</p> <pre><code>df[df.ID.isin([1, 6])].groupby('Name').Azimut.\ transform(lambda x: x.fillna(x.mode()[0])) </code></pre> <p>I specifically used <code>mode</code> since a duplicate can have...
python|pandas
0
368,232
73,613,582
How can I calculate the percentage of hour spent from location and time data
<p>I have 2 DataFrame.</p> <pre><code>import pandas as pd loc_hour = pd.DataFrame({'id': ['a', 'b', 'c',&quot;d&quot;], 'geohash': [&quot;sybewp&quot;, &quot;sws101&quot;, &quot;sxk9db&quot;,&quot;sxr4xt&quot;],&quot;log_date&quot;:[20210615,20211219,20210108,20210507],&quot;hour&quot;:[12,4,5,19]}) loc_grid = pd.Dat...
<p>It would have been helpful to provide input data that matches the question. For example, you asked for dataframes with period in last 30 and 90 days but none of your sample data had dates in the last 30 or 90 days.</p> <p>This is a pretty verbose approach but I did this so you could see what is happening at each ste...
python|pandas|percentage
0
368,233
73,758,414
simplify python code for reading data from files and store into numpy array
<p>i have inp file that needs to read from python data.inp</p> <pre><code>*Heading ** Job name: inp6_1 Model name: Model-1 *Node 1, 50., 20., 40. 2, 100., 20., 40. 3, 100., 20., 0. 4, 50., 20., ...
<p>You can just read split the entire string instead of reading it line by line:</p> <pre><code># Read as single string with open(filepath, 'r') as file: contents = file.read() # find *Node and *Element and get substring in between first = &quot;*Node&quot; second = &quot;*Element&quot; numbers = contents[contents...
python|numpy
2
368,234
73,711,133
Convert Dictionary with Differing Lengths to DataFRame
<p>I'm trying to convert a dictionary to a DataFrame in python, but the other answers on stack are for slightly different purposes and I can't seem to do it.</p> <pre><code>have &lt;- {0: [1, 2], 1: [1]} want &lt;- ['cluster' = [0, 0, 1], 'value' = [1, 2, 1]] </code></pre>
<p>Try this:</p> <pre><code>cluster = [] value = [] for i,j in my_dict.items(): for k in j: cluster.append(i) value.append(k) </code></pre> <p>Output</p> <pre><code>cluster # [0, 0, 1] value # [1, 2, 1] </code></pre>
python|pandas
0
368,235
73,573,026
Having an issue converting a set of very large integers into timedeltas
<p>I am working with a dataframe that includes a column of integers where the units are the number of days since 0001-01-01. I need to convert these integers into current dates. When I attempt use the pd.to_timedelta function to convert these integers into TimeDeltas that I can then add to the start date, the resulting...
<p>Every year is 365 days, except for leap years which are 366 days and occur every four years. So I just need to pick an arbitrary point within the acceptable timedelta resolutions, (e.x. 1850), calculate the number of regular years and leap years between 0000-01-01 and 1850-01-01, multiply regular by 365 and leap by ...
python|pandas|datetime
0
368,236
73,626,751
Having trouble interpreting a Numpy question
<p>Here's the question and the example given:</p> <blockquote> <p>You are given a 2-d array A of size NxN containing floating-point numbers. The array represents pairwise correlation between N elemenets with A[i,j] = A[j,i] = corr(i,j) and A[i,i] = 1.</p> <p>Write a Python program using NumPy to find the index of the h...
<p>To reiterate, the example is wrong in multiple ways.</p> <p>Correlation matrices are by definition symmetric, yet the example is not:</p> <pre><code>array([[1. , 0.3, 0.4], [0.4, 1. , 0.5], [0.1, 0.6, 1. ]]) </code></pre> <p>Also you are right, numpy arrays (like everything else I know in Python that s...
python|arrays|numpy
1
368,237
71,341,743
Convert JSON data to Pandas DataFrame where keys and values are in different sections of JSON
<p>I'm trying to create a python pandas DataFrame out of the JSON file but my eventual DataFrame column headers are in a different section of the JSON file to the values that will fill the columns.</p> <p>I have simplified the json, but it basically looks like below. There is only one section of column headers and mult...
<p>Construct a DataFrame by extracting the values under the &quot;values&quot; key; assign column names using the list under &quot;my_data_columns_headers&quot; key, which is under the &quot;my_data&quot; key.</p> <pre><code>out = pd.DataFrame(pd.Series(data['values']).str.get('data').tolist(), columns=data['my_data'][...
python|json|pandas|dataframe
1
368,238
71,147,020
Handle missing data when flattening nested array field in pandas dataframe
<p>We need to flatten this into a standard 2D DataFrame:</p> <pre><code>arr = [ [{ 'id': 3, 'abbr': 'ORL', 'record': { 'win': 3, 'loss': 7 }}, { 'id': 5, 'abbr': 'ATL', 'record': { 'win': 3, 'loss': 7 }}], [{ 'id': 7, 'abbr': 'NYK', 'record': { 'win': 3, 'loss': 7 }}, { 'id': 9, 'abbr': 'BOS', 'reco...
<p>The main issue with your code is that &quot;abbr&quot; key may not exist. You could account for that using <code>dict.get</code> method. If you replace:</p> <pre><code>zed = { 't1': team1['abbr'], 't2': team2['abbr'] } </code></pre> <p>with</p> <pre><code>zed = { 't1': team1.get('abbr', np.nan), 't2': team2.get('abb...
python|arrays|pandas|dataframe
1
368,239
71,397,529
Efficient way of applying arbitrary functions to a pandas DataFrameGroupBy object?
<p>I have a dataframe with an 'id' column and a number of other columns. For each id, I need to compute a number of features, using data from the corresponding rows. The features can be complicated functions, rather than simple aggregations.</p> <p>Preferably, the features should be computed relatively efficiently, and...
<p><code>result = example_data.groupby(&quot;id&quot;).apply(compute)</code>, but you'd have to play around with the (Multi)Index.</p>
python|pandas
1
368,240
71,352,394
Replacing columns in pandas
<p>I have a dataframe which has 80 columns. I want to replace some random columns with different values. I found some solution where we use df[&quot;c&quot;] = mylist. but what if i want to randomly select a column and i don't know the column name. Something like, <code>colNum = 12</code>, and then i do <code>df[colNum...
<p>Use <a href="https://numpy.org/doc/stable/reference/random/generated/numpy.random.choice.html" rel="nofollow noreferrer"><code>numpy.random.choice</code></a> to randomly select <code>N</code> columns:</p> <pre><code>N = 3 cols = np.random.choice(df.columns, size=N, replace=False) </code></pre> <p>Then, to loop:</p> ...
python|pandas|dataframe
0
368,241
71,308,170
Would like to concatenate (vstack) 3 dataframes, but when I try it is returning the 3 different dataframes one under another instead of concatenating
<p>Below is the code that I have tried and the image is the output when I try running this.</p> <p>There are 3 csv's I am loading with the index column name key</p> <pre><code>import numpy as np import pandas as pd from pathlib import Path import glob import os cwd = os.getcwd() directory = './csvdir' output_filename...
<p>Your function is printing the dataframe, one at the time, instead of concatenating them. Try:</p> <pre class="lang-py prettyprint-override"><code>def combine_csv_files(directory, output_filename): dfs = [] for f in Path(directory).glob(&quot;*.csv&quot;): try: df = pd.read_csv...
python|pandas
1
368,242
71,358,558
Pandas - instead of dropping rows with nan values I want to keep those rows and drop the others in a particular column
<p>I have several column in my df, one is <code>error</code>. If that column has rows with a value (this one always has 99 as the error message value) I want to remove those rows and keep the ones that are nan.</p> <p>df:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: le...
<p>A more general solution than proposed by <em>enke</em> is:</p> <pre><code>df = df[df.error.isna()] </code></pre> <p>This way you retain only rows with <em>NaN</em> in <em>error</em> column, regardless of the error value in original DataFrame.</p>
python|pandas
1
368,243
71,304,504
How to make moving window faster?
<p>I use a moving window to buffer raster data (numpy array). It is very slow and I am wondering if it is possible to improve the code to make it faster: My actual arrays have the shape (1349, 1368) and consist of zeros and ones.</p> <pre><code>import numpy as np clouds = np.array([[[0, 0, 0, 0, 0], ...
<p>Here are some specific guidelines to make your code faster:</p> <ol> <li><em>Avoid repeating the same calculation:</em> In your first two loops you do the same calculation (<code>np.where(clouds == 1)</code>) many times, so that you could refactor to:</li> </ol> <pre class="lang-py prettyprint-override"><code>row_id...
python|arrays|numpy|performance|loops
3
368,244
71,244,980
Make conditions in Pandas DataFrames optional (based on user input)
<p>In a script that accepts user input to query several columns of a spreadsheet, I am using Pandas to combine conditions, e.g.</p> <pre><code>output1=f.loc[f['pers_name'].isin(user_list) &amp; (f['event_start'].values==q_year)] </code></pre> <p>If there are just two conditions, I can easily use <code>if</code> and <co...
<p>In this kind of cases, we can use <a href="https://numpy.org/doc/stable/reference/generated/numpy.select.html" rel="nofollow noreferrer"><code>numpy.select</code></a> like in this example :</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd val1 = 1 val2 = 10 condlist = [df[...
python|pandas
1
368,245
71,402,829
β€ΊHow to join tables in Python without overwriting existing column data
<p>I need to join multiple tables but I can't get the join in Python to behave as expected. I need to left join table 2 to table 1, without overwriting the existing data in the &quot;geometry&quot; column of table 1. What I'm trying to achieve is sort of like a VLOOKUP in Excel. I want to pull matching values from m...
<p>You could try:</p> <pre><code># rename the Blockcode column in table1 to have the same column ID as table2. # This is necessary for the next step to work. table1 = table1.rename(columns={&quot;Blockcode&quot;: &quot;GeoID&quot;,}) # Overwrites all NaN values in table1 with the value from table2. table1.update(table...
python|pandas|join|left-join
1
368,246
71,221,625
Change panda DataFrame into paragraph with a certain format
<p>Here is the code:</p> <pre><code># Import pandas library import pandas as pd # initialize list of lists data = [['tom', 10], ['nick', 15], ['juli', 14]] # Create the pandas DataFrame df = pd.DataFrame(data, columns = ['Name', 'Age']) # print dataframe. df </code></pre> <p><a href="https://i.stack.imgur.com/mTtk6.png...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.capitalize.html" rel="nofollow noreferrer"><code>Series.str.capitalize</code></a> and join values of <code>Age</code> converted to strings:</p> <pre><code>df['new'] = df['Name'].str.capitalize() + ' ' + df['Age'].astype(str) pri...
python|pandas
0
368,247
71,420,593
Pandas dataframe groupby sum strings in reverse order
<p>I have a DataFrame like this:</p> <pre><code>colA colB 1 aaa 1 rrr 1 www 2 bbb 2 ccc 2 sss ... </code></pre> <p>I would like to convert the DataFrame as follows</p> <pre><code>colA Sum 1 wwwrrraaa 2 ssscccbbb ... </code></pre> <p>I tried</p> <pre><code>df.groupb...
<p>Reverse the DataFrame; then <code>groupby</code> + <code>sum</code>:</p> <pre><code>out = df[::-1].groupby('colA', as_index=False)['colB'].sum() </code></pre> <p>Output:</p> <pre><code> colA colB 0 1 wwwrrraaa 1 2 ssscccbbb </code></pre>
python|pandas|dataframe|group-by|pandas-groupby
2
368,248
71,123,261
How do I merge (insert) rows from one dataframe into another one in Pandas?
<p>Let's suppose I have a following dataframe:</p> <pre><code>df = pd.DataFrame({'id': [1, 2, 3, 4, 5], 'val': [0, 0, 0, 0, 0]}) </code></pre> <p>I want to <strong>modify</strong> the column <code>val</code> with values from another dataframes like these:</p> <pre><code>df1 = pd.DataFrame({'id': [2, 3], 'val': [1, 1]})...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.update.html" rel="nofollow noreferrer"><code>DataFrame.update</code></a> with convert <code>id</code> to index in all DataFrames:</p> <pre><code>df = df.set_index('id') df1 = df1.set_index('id') df2 = df2.set_index('id') df.upda...
python|pandas
1
368,249
71,195,997
JSON Parsing Trouble in Python
<p>I am trying to pull out an element from this JSON data and format it into another column in my pandas DataFrame.</p> <p>Here is the code I have so far:</p> <pre><code>#Import libraries import json import requests from IPython.display import JSON import pandas as pd #Load data astronaut_db_url = 'https://superclust...
<p>I'd go for using <code>awards</code> as a list of dictionaries and apply the function to every element of it.</p> <pre class="lang-py prettyprint-override"><code>import json import requests from IPython.display import JSON import pandas as pd #Load data astronaut_db_url = 'https://supercluster-iadb.s3.us-east-2.ama...
python|json|pandas|dataframe|python-requests
1
368,250
71,326,966
Plot graph for only one specific value in a column
<p>I am working with a dataset that looks at groceries, and the types of groceries, delivered at certain times of the day.</p> <p><a href="https://i.stack.imgur.com/mOGio.jpg" rel="nofollow noreferrer">Dataset</a></p> <p>I want to make a line graph of how much alcohol is delivered at certain hours of the day(order_hour...
<p>You can do something like this (really simplified):</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df2 = df.loc[(df['department']=='alcohol') &amp; (df['order_hour_of_day'] &gt;= 0) &amp; (df['order_hour_of_day'] &lt;= 23), :] plt.plot(df2['num_orders_hour'], df2['order_hour_of_day']) </code><...
python|pandas|matplotlib
1
368,251
71,358,487
Add new columns based on a lookup table in pandas
<p>I have two DataFrames:</p> <p><code>df1</code>:</p> <pre><code>block, name A, X B, Y C, X </code></pre> <p>and <code>df2</code>:</p> <pre><code>type, name, area G1, X, 0.10 G1, Y, 0.20 G2, X, 0.50 G2, Y, 0.75 </code></pre> <p>The end result I want to achieve is:</p> <pre><code>block, name, G1_area, G2_area A, X, 0.1...
<p>You could <code>merge</code> + <code>pivot</code>:</p> <pre><code>out = (df1.merge(df2, on='name') .pivot(['block', 'name'], 'type', 'area') .add_suffix('_area') .reset_index().rename_axis([None], axis=1)) </code></pre> <p>Output:</p> <pre><code> block name G1_area G2_area 0 A X 0...
python|pandas|dataframe
2
368,252
71,380,362
numpy "TypeError: ufunc 'bitwise_and' not supported for the input types" and the inputs could not be safely coerced to any supported types
<p>my input dataframe:</p> <pre><code> F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12 F13 F14 F15 F16 F1 1.0 1.0 1.0 1.0 1.0 1.0 0.0 1.0 0.0 0.0 0.0 1.0 1.0 0.0 1.0 1 F2 1.0 1.0 1.0 0.0 1.0 0.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 0.0 0.0 1 F3 0.0 1.0 1.0 1.0 0.0 1.0 1.0 0.0 1.0 0.0 0.0 1.0 1.0 1.0 1.0 1 F4 0.0 0.0 1.0 ...
<p>Convert values of array <code>m</code> to boolean for mapping <code>1/0</code> to <code>True/False</code>:</p> <pre><code>final = m.astype(bool) | bol </code></pre> <hr /> <pre><code>print (final) [[ True True True True True True True True True True True True True True True True] [ True True True...
python|pandas|numpy
1
368,253
71,122,153
Why Error: ValueError: Empty training data?
<p>I have got a training dataset of 1,000 images but while compiling my code, I came across this error; Error: ValueError: Empty training data?</p> <p>What's the possible solution? Thanks</p>
<p>The issue is that there is no validation or test dataset in your directory. Ensure you have data in your validation directory.</p>
python|tensorflow|keras
1
368,254
71,185,289
Iterate Over a Column In Pandas & Extract its Text in another Column
<p>I have created a Dataframe of 80,000 Links of PDFs &amp; Have also created a code to convert the Link of the PDF into a Text file. now the issue that i am not getting is that how to add another column to my dataframe which will correspond to the link of the PDF. Like if their is a row with link of PDF like - anc.pdf...
<p>You may construct a list of dictionary first and finally convert it into a dataframe:</p> <pre><code>allcapex_list = [] for i in result['Source']: try: urltopdf(i) except Exception as e: print('An error with urltopdf') print('Link:', i) print('Error:', e) continue #ad...
python|pandas|dataframe|pdf
0
368,255
71,250,527
Counting the sum of a list in pandas dataframe column
<p>I have a dataframe where column &quot;lists&quot; has lists:</p> <pre><code>l = ({'lists' : [[2,4,6],[8,10,12],[14,16,18]]}) df = pd.DataFrame(data = l) </code></pre> <p>I' trying to add a new column that is the sum of the elements in these lists:</p> <pre><code> lists sum 0 [2, 4, 6] 12 1 [8...
<p>Call <code>sum</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.apply.html" rel="nofollow noreferrer"><code>Series.apply</code></a>:</p> <pre><code>df['sum'] = df['lists'].apply(sum) </code></pre> <p>Or list comprehension without <code>zip</code>:</p> <pre><code>df['sum'] = ...
python|pandas
4
368,256
71,335,485
How can I replace nan values in a 2d ndarray with values of the closest non nan non zero value
<p>2D array has regularly distributed values, so the task is replace each NaN or 0 between values with the value of the closest element. If the position of element is strictly middle, so the least of two values will be taken for example.</p> <p>The input array could be plotted as a square grid with values and the task ...
<p>Let it be a zero array with each 6th element - a random int value:</p> <pre><code>a = np.zeros((121,121),dtype='float32') a[0::6,0::6] = np.random.randint(1,100,(21,21)) </code></pre> <p>And let make two matrices of indices of the a:</p> <pre><code>ind1, ind2 = np.meshgrid(range(0,a.shape[0],1),range(0,a.shape[1],1)...
python|numpy|scipy|nan
0
368,257
71,302,059
Numpy to pyTorch: are there different data types?
<p><strong>Question</strong>: Can somebody help me to align this two approaches of data generation so that both of them can be used by the nn-model below ? When using appraoch (2) with <code>numpy</code> and <code>torch.from_numpy(x)</code> a run time error occurs (&quot;<em>expected scalar type Float but found Double<...
<p>The default floating point type in <code>torch</code> is <code>float32</code> (i.e. single precision). In NumPy the default is <code>float64</code> (double precision). Try changing <code>get_training_data_2</code> so that it explicitly sets the data type of the numpy arrays <code>numpy.float32</code> before conver...
numpy|pytorch
1
368,258
71,442,528
A better way to create an NxN matrix, with specific diagonal and off diagonal elements with numpy
<p>I need to make a NxN matrix and specify diagonal elements. This is what I tried so far, I was hoping to find a more elegant solution without loops.</p> <pre><code>N = 4 value_offdiag = 2 b = np.eye(N, N) b[np.triu_indices(N, 1)] = value_offdiag b[np.tril_indices(4, -1)] = value_offdiag </code></pre> <p>This wo...
<p>What about using <a href="https://numpy.org/doc/stable/reference/generated/numpy.fill_diagonal.html" rel="nofollow noreferrer"><code>numpy.fill_diagonal</code></a>?</p> <pre><code>N = 4 value_offdiag = 2 b = np.ones((N,N))*value_offdiag np.fill_diagonal(b,1) print(b) </code></pre> <p>output:</p> <pre><code>[[1. 2. ...
python|numpy|matrix
3
368,259
71,099,818
WebSocket not working when trying to send generated answer by keras
<p>I am implementing a simple chatbot using keras and WebSockets. I now have a model that can make a prediction about the user input and send the according answer.</p> <p>When I do it through command line it works fine, however when I try to send the answer through my WebSocket, the WebSocket doesn't even start anymore...
<p>I am devastated, I just wasted 2 days into the dumbest possible issue (and fix)</p> <p>I still had the</p> <pre><code>while True: question = input(&quot;&quot;) ints = predict(question) answer = response(ints, json_data) print(answer) </code></pre> <p>in my model file, so the server didn't start. The...
python|tensorflow|machine-learning|keras|websocket
4
368,260
71,205,404
pytorch reduce_op warning message despite not calling it
<p>I'm constantly receiving a warning message per below; despite not calling the pytorch reduce_op anywhere.</p> <pre><code>C:\Users\cocoj\.conda\envs\py39\lib\site-packages\torch\distributed\distributed_c10d.py:170: UserWarning: torch.distributed.reduce_op is deprecated, please use torch.distributed.ReduceOp instead ...
<p>I am also not clear on what they meant, but since they were saying that it's safe to ignore you can try using the warnings module to ignore the message like so:</p> <pre><code>import warnings warnings.filterwarnings(&quot;ignore&quot;, message=&quot;torch.distributed.reduce_op is deprecated&quot;) </code></pre> <p>N...
pytorch
2
368,261
71,181,498
Compress excel file in python
<p>Right now my final output is in excel format. I wanted to compressed my excel file using gzip. Is there a way to do it ?</p> <pre><code>import pandas as pd import gzip import re def renaming_ad_unit(): with gzip.open('weekly_direct_house.xlsx.gz') as f: df = pd.read_excel(f) result = df['Ad unit...
<p>Yes, this is possible.</p> <p>To create a gzip file, you can open the file like this:</p> <pre class="lang-py prettyprint-override"><code>with gzip.open('filename.xlsx.gz', 'wb') as f: ... </code></pre> <p>Unfortunately, when I tried this, I found that I get the error <code>OSError: Negative seek in write mode</...
python|excel|pandas|gzip
4
368,262
71,242,299
Timeseries function
<p>I've got a dataframe which looks something like this:</p> <p>Column1<br /> 315349655</p> <p>315349655</p> <p>315349655</p> <p>315349655</p> <p>It's more rows and how to write a function which will check if any value is bigger than the first row and also show where are these values are located.</p>
<p>I'll create a dummy dataframe for this:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame( {&quot;Column1&quot;: [random.randint(1, 10) for _ in range(10)]}, index=[(pd.to_datetime(&quot;today&quot;) + pd.DateOffset(days=i)).date() for i in range(10)], ) &gt;&gt;&gt; df Column1 2022-02-24 3 20...
pandas
0
368,263
71,124,980
panda df: Subset frame by condition in 2 columns
<p>I want to subset my df based on the condition of 2 columns: Date and Person</p> <p><strong>Condition:</strong><br /> Date must be NON-BLANK except when Person =='Peter'</p> <p>Tried the code but doesn't work, it removes ALL rows with blank in Date</p> <pre><code>df= df[ (df[df.columns[1]]!='peter') &amp; (pd.isnull ...
<p>Chain condition by <code>|</code> for bitwise <code>OR</code> by columns names:</p> <pre><code>df = df[df['Person'].eq('peter') | df['Date'].notna()] </code></pre> <p>Or by positions - selected columns by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html" rel="nofollow nor...
python|pandas
1
368,264
71,149,173
how i can take rows with multi column
<p>how i can choose rows with a condition on columns for example in below data frame i want use a list of columns to find same condition between them <a href="https://i.stack.imgur.com/AjaUZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AjaUZ.png" alt="enter image description here" /></a></p> <pre>...
<p>I have not included <code>student</code> and <code>flag</code> because you can't compare string to int. You can do something like this</p> <pre><code>df_subset = df[(df['height'] &gt; 50) &amp; (df['trigger2'] &gt; 50) ].copy() </code></pre> <p>or when you have multiple conditions, I prefer this</p> <pre><code>cond...
python-3.x|pandas|list|dataframe
0
368,265
71,307,691
ImportError: cannot import name 'tf2' from 'tensorflow.python' (unknown location)
<p>from tensorflow.python import tf2 ImportError: cannot import name 'tf2' from 'tensorflow.python' (unknown location)</p>
<p>True, but also: Official TensorFlow Support discourages use of tf.python.* as it is private and intended for development purposes only. While it may work in some cases, it will &quot;break unannounced&quot; in many others, often leading to &quot;Module Not Found&quot;</p>
python|tensorflow|importerror
0
368,266
71,356,046
Error while Loading stack of dictionaries to DataFrame in for loop
<p>I am reading excel files in folder by filtering some files and looping though the files to get data. When I read excel, I am getting stack of dictionaries and I am trying to convert the dictionary to DataFrame but I am getting error. Below is my code</p> <p>How can I get dictionaries to DataFrame?</p> <pre><code>p =...
<p>It is hard to say for sure without seeing your excel file(s), but it looks like df_xl is a dict that has DataFrames as values keyed by integers? Can you at least add the output of <code>type(df_xl)</code> to your question?</p> <p>Assuming this is the case, it is still not clear from your output if the dataframes are...
python|pandas
0
368,267
71,205,826
how to check occurance of string across two or more columns for each row and assign the final column with 0
<pre><code>id. datcol1 datacol2 datacol-n final col(to be created in output) 1 false true true 0 2 false false false 2 3 true true true ...
<p>Considering df to be:</p> <pre><code>In [1542]: df Out[1542]: id. datcol1 datacol2 datacol-n 0 1 False True True 1 2 False False False 2 3 True True True 3 4 True False False </code></pre> <p>Use <a href="https://numpy.org/doc/stable/reference/...
python|python-3.x|pandas|string|numpy
0
368,268
71,165,302
saving and reading back numpy array
<p>I have ndarray like this. I am writing it to a dataframe, saving as a pickle, reading that pickle, and then creating new array again. Why does <code>np.array_equal(my_array2,X_train)</code> return false? i tried to debug and have written some code to understand the problem but having a hard time</p> <p>How should I ...
<p>In your code, <code>X_train[0]</code> is itself an array while <code>my_array2[0]</code> is a string.</p> <pre><code>print(X_train[0]) &gt;&gt;array([' I I want to know how much s it thank you'], dtype='&lt;U97064') print(my_array2[0]) &gt;&gt;' I I want to know how much s it thank you' </code></pre> <p>If you want ...
python|pandas|numpy
2
368,269
71,406,466
Visualize area of Russia correctly
<p>I should make specific map of Russia but I stucked on first step: I can't visualize the whole area correctly. For this I use that code:</p> <pre><code>import geopandas as gpd import matplotlib.pyplot as plt path = 'C:\\Users\\sashk\\Python_projects\\Data_map_based\\data\\RUS_adm2.shp' Map = gpd.read_file(path) print...
<p>I've found the answer and it's works:</p> <pre><code>import matplotlib.pyplot as plt import geopandas as gpd from shapely.geometry import LineString from shapely.ops import split from shapely.affinity import translate def shift_geom(shift, gdataframe, plotQ=False): shift -= 180 moved_geom = [] splitted_g...
matplotlib|data-visualization|geopandas|shapefile
0
368,270
71,431,982
Permutation of a number of rows of a dataframe using pandas
<p>I have a data frame of this kind:</p> <pre><code>d = pd.DataFrame({'Job': ['A', 'B', 'C', 'D', 'E'], 'Machine1': [1,3,2,4,3], 'Machine2': [2,0,5,1,2]}) </code></pre> <p>For the index <code>'Job'</code>, I need to find all permutations of length 5, basically (5 factorial) permutations. The length of the index...
<p>I think you're looking for the built-in function <code>itertools.permutations()</code>:</p> <pre><code>import itertools as it permutations = list(it.permutations(d['Job'])) </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; permutations [('A', 'B', 'C', 'D', 'E'), ('A', 'B', 'C', 'E', 'D'), ('A', 'B', 'D', 'C', ...
python|pandas|permutation
0
368,271
71,338,565
Converting worded date format to datetime format in pandas
<p>Today one of my script gave an error for an invalid datetime format as an input. The script is expecting the datetime input as '%m/%d/%Y', but it got it in an entirely different format. For example, the date should have been 5/2/2022 but it was May 2, 2022. To add a bit more information for clarity, the input is com...
<p>If you're in presence of the full month name, try this:</p> <pre><code>&gt;&gt;&gt; pd.to_datetime(df[&quot;Date&quot;], format=&quot;%B %d, %Y&quot;) 0 2022-05-02 Name: Date, dtype: datetime64[ns] </code></pre> <p>According to the <a href="https://docs.python.org/3/library/datetime.html#strftime-and-strptime-form...
python|pandas
0
368,272
71,429,103
Splitting one record as multiple records in Python
<p>In python, how can I convert this data like this :</p> <p><img src="https://i.stack.imgur.com/T4OfD.png" alt="1" /></p> <p>into this data like this:</p> <p><img src="https://i.stack.imgur.com/4qQYl.png" alt="2" /></p>
<p>You could use <code>np.split(..., 2, axis=1)</code> to split the dataframe vertically into 2 parts:</p> <pre><code>new_df = pd.concat([x.T.reset_index(drop=True).T for x in np.split(df.set_index('ID'), 2, axis=1)]).sort_index() </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; new_df 0 1 2 ID 1 0...
python|pandas|pandas-datareader
1
368,273
71,227,628
How to make operations between columns in pandas so to avoid warning message 'Try using .loc[row_indexer,col_indexer] = value instead'
<p>I have a dataframe that looks like this:</p> <pre><code>Time y1 y2 100 130 44.57 200 130 42.23 300 130 42.83 </code></pre> <p>I am simply trying to convert column Time from s into minutes, and make an operation between column y1 and y2. However I keep getting a warning message: A value is trying to be s...
<p>Add this line before you do your calculations:</p> <pre><code>df1 = df1.copy() </code></pre>
pandas|indexing
0
368,274
71,154,622
How to convert this tabular panda dataframe with row name into this json format?
<p>I have the panda dataframe <code>df</code> below;</p> <pre><code> File Hour Name1 F1 1 Name2 F1 2 </code></pre> <p>I want to convert it into json that looks like this;</p> <pre><code>{ &quot;Name1&quot;: { &quot;File&quot;: &quot;F1&quot;, &quot;Hour&quot;: &quot;...
<p>As hinted <a href="https://stackoverflow.com/questions/39257147/convert-pandas-dataframe-to-json-format">here</a>, you can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_json.html" rel="nofollow noreferrer"><code>to_json</code></a> this way:</p> <pre><code>df.to_json(orient='index') </...
python|json|pandas
1
368,275
71,226,513
Any workaround to efficiently calculate distance between list of coordinates in python?
<p>I have data comes with zip/post code, longitude, latitude info. I want to calculate zip distance between one zip code against the rest then do same recursively without duplicated distance values in python. However, I am able to use <code>geosphere</code> R library for distance calculation. However, my objective is t...
<p>Not a full answer, just to test</p> <p>Try with sklearn:</p> <pre><code>from sklearn.neighbors import BallTree, DistanceMetric # gist='https://gist.githubusercontent.com/adamFlyn/...' df = pd.read_csv(gist, index_col=0) coords = np.radians(df[['latitude', 'longtitude']]) dist = DistanceMetric.get_metric('haversine...
python|pandas|data-manipulation|geopandas
1
368,276
71,183,060
Interpolation of arrays python
<p>I have a program where I want the user to choose a temperature (<code>T_user</code>), whatever he wants. Knowing that I have a temperature array: <code>T=np.array([10,20,30,50,100,150,200])</code>. I have found a way to get the index and closest value for <code>T_user</code> compared to the values in <code>T</code>....
<p>You can use the <code>apply_along_axis</code> method:</p> <h2>Code:</h2> <pre class="lang-py prettyprint-override"><code>import numpy as np T = np.array([10, 20, 30, 50, 100, 150, 200]) W1 = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) W2 = np.array([3, 6, 9, 12, 15, 18, 21, 24, 27, 30]) T_user = 12 # Get the neighb...
python|numpy|linear-interpolation
0
368,277
52,082,477
Python list error for count vectorizer and fit function
<p>Please tell what is wrong and how to rectify. </p> <pre><code>data = open(r"C:\Users\HS\Desktop\WORK\R\R DATA\g textonly2.txt").read() labels, texts = [], [] #print(data) for i, line in enumerate(data.split("\n")): content = line.split() #print(content) if len(content) is not 0: labels.append(co...
<p>From the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html#sklearn.feature_extraction.text.CountVectorizer.fit" rel="nofollow noreferrer">documentation</a>:</p> <blockquote> <p>fit(raw_documents, y=None)[source] Learn a vocabulary dictionary of all to...
python-3.x|pandas|machine-learning|scikit-learn
1
368,278
52,177,257
Noob stuck Tensor flow adjusting the array shape
<p>first thank you for any help that you can give. I am absolutely lost on the shape in tensensorflow. I have searched google, StackOverflow, discord, and youtube. I want to run a RNN on a CSV file. </p> <pre><code>import pandas as pd import numpy as np import tensorflow as tf from tensorflow import keras as keras da...
<p>None is your Batchsize. Your array you want to feed in begins afterwards. For example [None,255,255] will be a 255 by 255 picture with variable batchsize. </p>
python|tensorflow
1
368,279
52,398,441
tensorflow convolution result to numpy
<p>I write a simple code,</p> <pre><code>import numpy as np import tensorflow as tf x_data = np.loadtxt('D:\proj\dnn_lib_cuda\input') w_data = np.loadtxt('D:\proj\dnn_lib_cuda\weight') x_tensor = np.reshape(x_data, (1, 3, 224, 224)) w_tensor = np.reshape(w_data, (64, 3, 3, 3)) x_tensor_ch = x_tensor.transpose(0, 2,...
<p><code>sess.run(...)</code> returns the result of evaluating the tensor <code>result</code> given the data passed to <code>feed_dict</code>.</p> <p>So, what you want is</p> <pre><code>output = sess.run(result, feed_dict = {x: x_tensor_ch, w:w_tensor_ch}) </code></pre>
python|numpy|tensorflow
1
368,280
52,059,723
Calculate difference of Row Values with 1 Minute Interval Time
<p>I have a Dataframe like mentioned below:</p> <pre><code>TIME PRCESS_NO VALUE 13:40:34 1111 10254 13:40:37 1111 25855 13:40:45 1111 10254 13:40:53 1111 10254 13:40:58 1111 68522 13:41:08 1111 10254 13:41:34 1111 10254 13:41:56 1111 ...
<p>You can use <code>pd.Series.dt.floor</code> to floor times by minute. Assumes you specify minute intervals every time you reach 0 seconds.</p> <p>Then drop duplicates and us <code>GroupBy</code> + <code>diff</code>.</p> <pre><code>df['DT'] = pd.to_datetime(str(pd.to_datetime('today')) + ' ' + df['TIME']) df['DT'] ...
python|python-3.x|pandas|time|pandas-groupby
2
368,281
52,088,681
How to apply function on mutlple-index pandas dataframe elegantly like on panel?
<p>Suppose I have a dataframe like:</p> <pre><code>ticker MS AAPL field price volume price volume 0 -0.861210 -0.319607 -0.855145 0.635594 1 -1.986693 -0.526885 -1.765813 1.696533 2 -0.154544 -1.152361 -1.391477 -2.016119 3 0.621641 -0.109499 0.143...
<p>You can using <code>IndexSlice</code></p> <pre><code>df.loc[:,pd.IndexSlice[:,'price']].apply(pd.Series.pct_change).rename(columns={'price':'ret'}) Out[1181]: ticker MS AAPL field ret ret 0 NaN NaN 1 -1.420166 -0.279805 2 3.011155 0.062529 3 -1.609004 0.7...
pandas|dataframe
2
368,282
52,192,762
Smart way of creating multiple graphs using matplotlib
<p>I have an excel worksheet, let us say its name is 'ws_actual'. The data looks as below.</p> <pre><code>Project Name Date Paid Actuals Item Amount Cumulative Sum A 2016-04-10 00:00:00 124.2 124.2 A 2016-04-27 00:00:00 2727.5 2851.7 A 2016-05-11 00:00:00 2123.58 4975.28 A 2016-05-24 00:00:00 2500 7...
<p>You could just iterate the projects:</p> <pre><code>for proj in ws_actual['Project'].unique(): ws_actual[ws_actual['Project'] == proj].plot(x='Date Paid', y='Cumulative Sum', color='g') plt.show() </code></pre> <p>Or check out seaborn for an easy way to make a <a href="https://seaborn.pydata.org/generated/...
python|pandas|matplotlib
2
368,283
52,177,503
How to get name when roll number is given in pandas
<p>My code is:</p> <pre><code>df=pd.read_excel('vip.xlsx') df b=df['Roll No'] a=[x for x in map(str,b) if x[:8] == '12153162'] d=df['Name'] c=[y for y in map(str,d)] if a in df['Roll No']: print(df['Name']) </code></pre> <p>I got a type error for this:</p> <pre><code>TypeError: unhashable type: 'list' </code><...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with convert values to strings by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="nofollow noreferrer"><code>astype</code...
python-3.x|pandas|dataframe|data-manipulation
1
368,284
52,108,679
How to remove duplicate columns generated after using pd.get_dummies using their variance as cutoff
<p>I have a dataframe which is being generated using pd.get_dummies as below:</p> <pre><code>df_target = pd.get_dummies(df_column[column], dummy_na=True,prefix=column) </code></pre> <p>where column is a column name and df_column is the dataframe from which each column is being pulled to do some operations.</p> <pre>...
<p>For <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.var.html" rel="nofollow noreferrer"><code>DataFrame.var</code></a> use:</p> <pre><code>print (df.var()) rev_grp_m2_&gt; 225 0.083333 rev_grp_m2_nan 0.000000 rev_grp_m2_nan 0.000000 </code></pre> <p>Last for filtering i...
pandas|var
1
368,285
52,377,432
Add Category Column Based On Date - Pandas Dataframe
<p>I have a dataframe with a column ORDER_DATE. I'm trying to add a new column for FISCAL_YEAR which essentially has this type of criteria:</p> <ul> <li>If between 7/1/16 and 6/30/17 = FY2017</li> <li>If between 7/1/17 and 6/30/18 = FY2018</li> </ul> <p>The only way I could think to do it is a series of conditional s...
<p>You can assign a <code>PeriodIndex</code> to the dataframe with a June annual frequency (<code>A-Jun</code>), e.g.:</p> <pre><code>df = pd.DataFrame({'date': pd.DatetimeIndex(start='2015-01', end='2016-12', freq='D')}) df = df.assign(fiscal_year=pd.PeriodIndex(df.date, freq='A-Jun')) </code></pre> <p>If you need t...
python|pandas|dataframe
1
368,286
52,002,819
How many different days customer visits app
<p>I have a dataframe that looks like. Each object_id represents different customer.</p> <pre><code>date objectId 15/07/18 "__gb5c9e15dfc004930b8ac9d5d1df1880e" 16/07/18 "__g0b2abb9da5d646eb930c1ce9bb6df5ef" 16/07/18 "__c5ff64e5448c44fabe26e88bc0e41497" 17/07/18 "__c7b0a5824a914d7198a328cdf35c95bf" 18/0...
<p>You can use <code>GroupBy</code> with <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.nunique.html" rel="nofollow noreferrer"><code>nunique</code></a>:</p> <pre><code>res = df.groupby('objectId')['date'].nunique() print(res) objectId -g940dc0277b7f46c8b7d8de195a8fd975 2 __8929216...
python|pandas|pandas-groupby
1
368,287
52,285,258
python 3 and tensorflow on AWS EMR
<p>For EMR AWS has tensorflow 1.9 as part of the software stack for release 5.17. I have my own bootstrap script to install python 3.6 and tensorflow 1.9, I took out the tensorflow installation - but it didn't work -- I get on the master node, run <code>python3</code>, I get into my new python 3.6 but there is no tenso...
<p>From <a href="https://aws.amazon.com/premiumsupport/knowledge-center/emr-pyspark-python-3x/" rel="nofollow noreferrer">AWS</a>:</p> <blockquote> <p>Amazon EMR release versions 4.6.0-5.19.0: Python 3.4 is installed on the cluster instances. Python 2.7 is the system default.</p> <p>Amazon EMR release versions 5.20.0 a...
python-3.x|amazon-web-services|tensorflow|amazon-emr
1
368,288
52,428,484
Tensorflow is not running in windows 10
<p>I'm new to tensorflow. I installed python and tensorflow. I'm getting below error after running my sample code. </p> <p>I have installed tensorflow by below command. I saw that the below command seems for mac, but I have used this command only to install tensorflow, it is successfully installed. I did not get link ...
<p>Firstly, For windows there isn't a direct link, you have to do it from source. Refer to this link for windows: <a href="https://www.tensorflow.org/install/source_windows" rel="nofollow noreferrer">https://www.tensorflow.org/install/source_windows</a></p> <p>Are you sure you have installed python correctly? I prefe...
python|python-3.x|tensorflow|artificial-intelligence
0
368,289
52,020,482
Modify the contents of null columns in pandas by checking values in multiple colums
<p>How to obtain the below operation on dataframe easily in pandas using fewer steps?</p> <p>Input:</p> <pre><code>di = {'col1': ['1', '2', '5',None, None,'10', None,None], 'col2': ['4', '7', None, '8', None, None, '11',None], 'col3': ['9', None, '3', '8', None,None, None,'12'], 'col4': ['abc', 'def', 'ghi', ...
<p>I am not sure if I understood you correctly, but if you want replace all None values by "Hello" you could simply use:</p> <pre><code>df.fillna("Hello") </code></pre>
python|pandas|dataframe
0
368,290
52,009,553
How to read logs before Deadline Exceeded on Init TPU system
<p>I'm trying to run a model with Python 2.7 on a TPU with my own .tfrecord data file and all my code compiles, but the moment the TPU start doing its magic I don't have a clue what is going behind the scenes. </p> <p>Is there a way to track what is going on behind the scenes with a tf.debugger or something similar?</...
<p><strong>General Debugging</strong></p> <p>There are a few ways you can get more information on what the TPU is doing.</p> <p>The most straightforward is adding <a href="https://www.tensorflow.org/api_docs/python/tf/logging" rel="nofollow noreferrer">tf.logging</a> statements. If you're using TPUEstimator you'll li...
python-2.7|debugging|tensorflow|tfrecord|google-cloud-tpu
0
368,291
52,419,756
Minimax algorithm not working for 4x4 TicTacToe
<p>Okay, So I wrote the following agent for a bot to play tic tac toe. I have used the traditional minimax algorithm without pruning. The thing is that it works perfectly for a 3x3 board.</p> <p>But when I run this on a 4x4 board, it gets stuck computing. I am not able to understand why. I am passing the agent a numpy...
<blockquote> <p>I have used the traditional minimax algorithm <b> without pruning </b>. </p> </blockquote> <p>And that is already the answer to your question. This is why pruning and remembering past states is such an important topic in algorithmic design.</p> <p>If you increase the board size to 4x4 you'll have ex...
python|numpy|artificial-intelligence|minimax
2
368,292
52,084,133
pandas - create new column based on duplicates
<p>I would like to combine records that have an identical id number. For example, suppose I have this DataFrame:</p> <pre><code>df=pd.DataFrame({'id': [1, 2, 2, 4], 'animal': ['dog', 'cat', 'bear', 'mouse']}) # just rearranging the order a bit df=df[['id', 'animal', 'name']] id animal name 1 dog john 2 c...
<p>You could do:</p> <pre><code>df.groupby('id')['animal'].apply(lambda x: pd.Series(list(x))).unstack() </code></pre> <p>Which gives you:</p> <pre><code> 0 1 id 1 dog None 2 cat bear 4 mouse None </code></pre>
python|pandas
3
368,293
52,056,373
python - melt / reshape using multiple columns
<p>I've used melt to do this before, but only one column. How do you go about reshaping or melting on multiple columns? I'm thinking it's not necessarily reshape or melt, as I'm just duplicating a row, then switching values in <code>h</code> and <code>v</code> columns. My thought is to use <code>df.iterrows()</code> to...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.difference.html" rel="nofollow noreferrer"><code>difference</code></a> for all columns without <code>h</code> and <code>v</code> to parameter <code>id_vars</code> of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.D...
python|pandas
2
368,294
52,287,070
How to pass pandas dataframe to button in web for download file(.csv or .xlsx) with flask, Python 2.7
<p>My web application has visualization function for user see chart(Average, Standard Deviation) by <code>from ...day</code> <code>to ...day</code>(Start Date to End Date), where(Production line) then request to SQL for connect database. <strong>This is visualization form.</strong> :</p> <p><a href="https://i.stack.im...
<p>You can first make your dataframe in a csv format with the following function:</p> <pre><code>def build_csv_data(dataframe): csv_data = dataframe.to_csv(index=False, encoding='utf-8') csv_data = "data:text/csv;charset=utf-8," + quote(csv_data) return csv_data </code></pre> <p>Then create a callback fun...
python|pandas|csv|flask|xlsx
3
368,295
52,400,391
Could not find a version that satisfies the requirement tensorflow (from versions:) No matching distribution found for tensorflow
<p>While installing TensorFlow for my pc the following error appeared </p> <blockquote> <p>Could not find a version that satisfies the requirement TensorFlow (from versions:) No matching distribution found for TensorFlow </p> </blockquote> <p>I have a 64-bit Widows operating system. And Python 3.7.0 64-bit. I al...
<p>Refer the link for TensorFlow supported version for python</p> <pre><code>https://www.tensorflow.org/install/pip </code></pre> <p>upgrade pip to version 20</p> <pre><code>C:\&gt;pip --version pip 20.0.2 from c:\python37_64\lib\site-packages\pip (python 3.7) </code></pre> <p>then execute the following command</p>...
python|python-3.x|tensorflow|installation
0
368,296
52,202,432
how to add Highway Wrapper to multilayered bidirectional lstm in tensorflow
<p>I'm trying to add Highway Wrapper or Residual Wrapper to a bidirectional LSTM in tensorflow. The code is as below:</p> <pre><code>def lstm_cell(self): cell = tf.contrib.rnn.LSTMCell(num_units=self.num_units, forget_bias=1.0, state_is_tuple=True, initializer=orthogonal_initializer()) cell = tf.contrib.rnn.Hi...
<p>I think you can try to implement the rnn_fw and rnn_bw yourself, and add the residual connections to them separately. Then you can concatenate their outputs, and use the concatenated vector as the input to the higher level bi-rnn.</p>
python|tensorflow|lstm|rnn|bidirectional
0
368,297
52,129,876
UserWarning: Pandas doesn't allow columns to be created via a new attribute name
<p>I am stuck with my pandas script.</p> <p>Actually , i am working with two csv file(one input and the other output file). i want to copy all the rows of two column and want to make calculation and then copy it to another dataframe (output file).</p> <p>The columns are as follows :</p> <pre><code>'lat', 'long','PHC...
<p>Simply use <code>df2['a']</code> instead of <code>df2.a</code></p>
python|pandas|dataframe|indexing|lambda
49
368,298
52,145,568
Slicing the substring from the string in each row of the column using Python
<p>I am absolute beginner. I have a problem in slicing string in a Excel file using Python. My Excel file contains the following info:</p> <pre><code>Column 1: ordercode PMC11-AA1L1FAVWJA PMC21-AA1A1CBVXJA PMP11-AA1L1FAWJJ PMP21-AA1A1FBWJJ PMP23-AA1A1FA3EJ+JA PTP31B-AA3D1HGBVXJ PTC31B-AA3D1CGBWBJA ...
<p>Python gives you a lot more options than Excel. If you have a string <code>code = "PMC21-AA1A1CBVXJA"</code>, you can write</p> <pre><code>pressurerange, rest = code.split("-") </code></pre> <p>and you have the part before the <code>-</code> and the part after. I'll let you figure out how to use this in your workf...
python|pandas
1
368,299
52,394,909
Slice dataframe based on list of dates with different frequencies
<p>I try to slice a dataframe by rows based on dates of interest. <code>df_data</code> has an index based on <code>datetime</code> with the format <code>YYYY-MM-DD hh:mm:ss</code>.<br> It contains data from 2012-01-01 until 2018-06-30 on a 1 minute frequency. The other <code>dataframe</code> is containing a column w...
<p>I'm sure there is a more elegant solution, but I suspect your dates of interest are being interpreted as midnight (date and minute). If so, you'll want to pull out the days from that df_data, then try to your slicing again. </p> <pre><code># get a column of the days from your df_data df_data['just_day'] = df_data.i...
python|pandas|datetime|dataframe|slice
0