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
357,000
62,594,463
Replace not working as expected with commas, inverted commas and
<p>I have a dataframe train and it has characters like commas, inverted commas etc. So i have tried to replace them as below,</p> <pre><code>train['content']=train['content'].replace('…','') train['content']=train['content'].replace('”','') train['content']=train['content'].replace('“','') train['content']=train['conte...
<p>You can convert it into a list, them use a list comprehension:</p> <pre><code>train['content'] = [i for a in ['…','”','“','’'] for i in train['content'].tolist() if a not in i] </code></pre> <p>UPDATE:</p> <pre><code>train['content'] = [i if a not in i else None for a in ['…','”','“','’'] for i in train['content'].t...
python|pandas
1
357,001
62,725,539
Pandas to MYSQL index=False keeps error "unknown column"
<p>my sqlalchemy string is:</p> <pre><code>sql_insert.to_sql(name='Table1', con=engine, if_exists = 'append', index=False) </code></pre> <p>return error</p> <blockquote> <p>(mysql.connector.errors.ProgrammingError) 1054 (42S22): Unknown column 'Unnamed: 0' in 'field list'</p> </blockquote> <p>there is no specific index...
<p>Well, it didn't workout anything I have tried, so I just made sql with specific columns to be used. Still don't know what happened.</p>
mysql|pandas|dataframe|sqlalchemy
0
357,002
62,747,937
Tensorflow 2.2.0 support on non-AVX systems
<p>I need a TensorFlow version 2&gt; and I installed that on my Ubuntu Server, but it gives me the AVX error. I tried the 1.5 version and it works but doesn't support Keras and the other commands I used. I am using python3.5. There are no errors in the code.</p> <p>OS: Ubuntu Server on a Server with 16GB ram Pip: 19.0 ...
<p>To fix this, you can install TensorFlow via anaconda and not pip. It work for me by doing this. If anybody knows why, they are welcome to explain.</p>
python-3.x|linux|tensorflow|pip|avx
3
357,003
62,822,421
Select rows from 3-d nd-array
<p>the situation is as following: If I have a numpy array of shape (64, 100, 300) and I want to transform it to (64, 1, 300) based on an array of indices of shape 64, what should I do? Say we have</p> <pre><code>a=np.random.randn(64, 100, 300) indices = np.random.randint(low=0, high=100, size=64) </code></pre> <p>I cur...
<p>Like the comment above suggests:</p> <pre><code>a[np.arange(indices.size),indices,None] </code></pre> <p>Or equally but more readable:</p> <pre><code>a[np.arange(indices.size),indices][:,None,:] </code></pre>
numpy
3
357,004
62,750,397
How to get words matches with it's count using pandas
<p>i have 2 Dataframes like</p> <pre><code>set1 = ['a','b','c','d','e','f','g','h','i','j'] set2 = ['a','b','b','c','c','f','h','j','k'] df1 = pd.DataFrame(set1, columns=['name']) df2 = pd.DataFrame(set2, columns=['name']) </code></pre> <p>i want to compare these 2 Dataframes without forloop and get a output like</p> ...
<p>Use <code>pandas.DataFrame.merge</code> with <code>value_counts</code>:</p> <pre><code>df1.merge(df2, on=&quot;name&quot;)[&quot;name&quot;].value_counts() </code></pre> <p>Output:</p> <pre><code>b 2 c 2 j 1 a 1 h 1 f 1 Name: name, dtype: int64 </code></pre>
python|pandas|list|dataframe|isin
2
357,005
62,521,934
Pandas MultiIndex with an unrecognised time format - how to convert time and apply calculation
<p>EDIT: Thanks to Scott Boston for advising me on to correctly post.</p> <p>I have a dataframe containing clock in/out date and times from work for all employees. Sample df input is below, but the real data set has a year of data for many employees.</p> <p>Question: What I would like to do is to calculate the time spe...
<pre><code>df['Time'] = pd.to_timedelta(df['Time']) df['Date'] = pd.to_datetime(df['Date']) df['time_complete'] = df['Time'] + df['Date'] df.groupby(['name', 'Date']).apply(lambda x: (x.sort_values('type', ascending=True)['time_complete'].diff().dropna())) </code></pre> <p>how it works:</p> <p>Convert the dates to date...
python|pandas
2
357,006
62,874,740
Pandas Dataframe cannot find my first id_vars but I think it is in there. Any idea on how to fix this?
<p>This is the dataframe I'm working with. When I try to melt using this code:</p> <pre><code>dataframe = pd.melt(dataframe, id_vars = ['Country Name'], var_name = 'Name') </code></pre> <p>I get this error:</p> <pre><code>KeyError: &quot;The following 'id_vars' are not present in the DataFrame: ['Country Name']&quo...
<pre><code>#The melt method needs to be called by the DateFrame object created import numpy as np import pandas as pd df = pd.DataFrame({'Class':[1,2],'Name':['San Zhang', 'Si Li'],'Chinese':[80, 90],'Math':[80, 75]}) df df_melted = df.melt(id_vars = ['Class', 'Name'],value_vars = ['Chinese', 'Math'],var_name = 'Subje...
python|pandas
-1
357,007
62,847,437
How to calculate the common volume/intersection between 2, 2D kde plots in python?
<p>I have 2 sets of datapoints:</p> <pre><code>import random import pandas as pd A = pd.DataFrame({'x':[random.uniform(0, 1) for i in range(0,100)], 'y':[random.uniform(0, 1) for i in range(0,100)]}) B = pd.DataFrame({'x':[random.uniform(0, 1) for i in range(0,100)], 'y':[random.uniform(0, 1) for i in range(0,100)]}) <...
<p>I believe this is what you're looking for. I'm basically calculating the space (integration) of the intersection (overlay) of the two KDE distributions.</p> <pre><code>A = pd.DataFrame({'x':[random.uniform(0, 1) for i in range(0,100)], 'y':[random.uniform(0, 1) for i in range(0,100)]}) B = pd.DataFrame({'x':[random....
python-3.x|pandas|matplotlib|seaborn|shapely
2
357,008
62,839,546
Python dataframe drop rows which occur less frequently
<p>I have a data frame with repeatedly occurring rows with different names. I want to delete less occurring rows. My data frame is very big. I am giving only a small size here.</p> <p><strong>dataframe:</strong></p> <pre><code>df = name value 0 A 10 1 B 20 2 A 30 ...
<p>You could find the count of each element in name and then select rows only those rows having names that occur more than once.</p> <pre class="lang-py prettyprint-override"><code>v = df.name.value_counts() df[df.name.isin(v.index[v.gt(1)])] </code></pre> <p><strong>Output :</strong></p> <pre><code> name value 0...
python|pandas|dataframe|pandas-groupby
5
357,009
62,886,408
Using regular expressions to remove a string from a column
<p>I am trying to remove a string from a column using regular expressions and replace.</p> <pre><code> Name &quot;George @ ACkDk02gfe&quot; sold </code></pre> <p>I want to remove <code>&quot; @ ACkDk02gfe&quot;</code></p> <p>I have tried several different variations of the code below, but I cant s...
<p>Let's try this using regex with | (&quot;OR&quot;) and regex group:</p> <pre><code>df['Name'].str.replace('&quot;|(\s@\s\w+)','', regex=True) </code></pre> <p>Output:</p> <pre><code>0 George sold Name: Name, dtype: object </code></pre> <h3>Updated</h3> <pre><code>df['Name'].str.replace('&quot;|(\s@\s\w*[-]?\w+)',...
python|regex|pandas
3
357,010
62,875,836
Matching sequence of two dataframes with similar string parttern keeping index and sequence
<p>I have two dataframes df and df1. where I have to match sequence or strings and getting the only matching string sequence with index number of df as output.</p> <p>df</p> <pre><code>idx id_0 user string 0 008457 02 hello 1 990037 05 I 2 774426 10 am 3 564389 08 sleeping 4 009124 17 today 5 000029 13 is 6 548751 21 ...
<p>A possible way to do that is as follows:</p> <pre><code>df = pd.DataFrame([ [0, &quot;008457&quot;, &quot;02&quot;, &quot;hello&quot;], [1, &quot;990037&quot;, &quot;05&quot;, &quot;I&quot;], [2, &quot;774426&quot;, &quot;10&quot;, &quot;am&quot;], [3, &quot;564389&quot;, &quot;08&quot;, &quot;sleepi...
python|pandas|scikit-learn
2
357,011
54,558,398
concatenate column values in a loop
<p>I have a csv file with two columns:</p> <pre><code> col1 col2 ----- | ----- link1 unix=number1 link2 unix=number2 link3 unix=number3 </code></pre> <p><strong>What I need:</strong></p> <p>I need to concatenate each value in col1 with each value in col2 to have the following result:</p> <pre><...
<p>Use:</p> <pre><code>import itertools df['col3']=[''.join(i) for i in list(itertools.product(df['col1'],df['col2']))] </code></pre> <p>EDIT:</p> <pre><code>l= [''.join(i) for i in list(itertools.product(df1.col1,df1.col2))] df=df.reindex(range(len(l))) df['col3']=l print(df) col1 col2 col3 0 a x ax 1 ...
python-3.x|pandas|loops
2
357,012
54,298,858
Mapping values in a numpy array
<p>How do I go from a 2D numpy array where I only have three distinct values: -1, 0, and 1 and map them to the colors <code>red</code> (255,0,0), <code>green</code> (0,255,0), and <code>blue</code> (255,0,0)? The array is quite large, but to give you an idea of what I am looking for, imagine I have the input</p> <pre>...
<p>You might want to consider a structured array, as it allows tuples without the datatype being <code>object</code>.</p> <pre><code>import numpy as np replacements = {-1: (255, 0, 0), 0: (0, 255, 0), 1: (0, 0, 255)} arr = np.array([[ 1, 0, -1], [-1, 1, 1], [ 0, 0, 1]]) new = np...
python|numpy|lambda|mapping|key-value
4
357,013
54,325,537
Pandas - retrieving previous result / row from each user
<p>I'm new to Pandas.</p> <p>I have a data frame which has looks like this (only much bigger):</p> <pre><code> Horses RaceDate Position 1 RedHorse 1/2/00 2 2 BlueHorse 1/2/00 6 3 YellowHorse 1/2/00 7 4 RedHorse 15/1/00 3 </code></pre> <p>I want to add column for previous resu...
<p>You can use <code>groupby</code> + <code>shift</code>:</p> <pre><code># convert dates to datetime and sort descending df['RaceDate'] = pd.to_datetime(df['RaceDate'], dayfirst=True) df = df.sort_values('RaceDate', ascending=False) # groupby and shift for previous position df['PrevPosition'] = df.groupby('Horses')['...
python|pandas|pandas-groupby
2
357,014
54,564,963
xarray - find data that is not 0 in a multi-dimensional xarray object with massive data efficiently
<p>My DataArray object is as below:</p> <pre><code>print(da_criteria_1or0_hourly) &lt;xarray.DataArray (time: 8760, latitude: 106, longitude: 193)&gt; dask.array&lt;shape=(8760, 106, 193), dtype=int32, chunksize=(744, 106, 193)&gt; Coordinates: * latitude (latitude) float32 -39.2 -39.149525 ... -33.950478 -33.9 ...
<p>You may want to have a look at the <code>stack</code> function. It stacks the xarray with all entries below each other and you then might be able to filter for all values that do not meet your requirements. I have not tested it with a super large data-set, but it does not use a triple for-loop, so might give you som...
python|pandas|numpy|python-xarray
0
357,015
54,655,218
add rows to pandas multindex
<p>I want to balance some production flows of some countries which are stored in a pandas dataframe with multindex. </p> <p>a simplified example of my problem could be something like this</p> <pre><code>dict_df1={2016: {('country A', 'peanuts', 'supply'): 3.0, ('country A', 'peanuts', 'demand'): 2.0, ...
<p>Using <code>groupby</code> <code>diff</code> create the df you want to append , then we using <code>concat</code> </p> <pre><code>conbinedf=df.groupby(level=[0,1]).diff().dropna().reset_index(level=2).assign(level_2='diff').set_index('level_2',append=True) yourdf=pd.concat([df,conbinedf]).sort_index(level=[0,1]) yo...
python-3.x|pandas
0
357,016
54,473,620
About custom operations in Tensorflow and PyTorch
<p>I have to implement an energy function, termed Rigidity Energy, as in Eq 7 of this paper <a href="https://www.igl.ethz.ch/projects/ARAP/arap_web.pdf" rel="nofollow noreferrer">here</a>.<br> The energy function takes as input two 3D object meshes, and returns the energy between them. The first mesh is the source mesh...
<p>As far as I understand, you are essentially asking if this operation can be vectorized. The answer is no, at least not fully, because <a href="https://pytorch.org/docs/master/torch.html#torch.svd" rel="nofollow noreferrer">svd</a> implementation in PyTorch is not vectorized.</p> <p>If you showed the tensorflow impl...
python|c++|tensorflow|pytorch|torch
1
357,017
54,510,317
How do I drop all numbers as data cleansing on pandas effectively?
<p>Here's my dataset</p> <pre><code>id descriptions 0 kartu debit 20 10 indomaretcipete r 1 tarikan atm 20 10 2 tarikan atm 19 10 3 ...
<p>IIUC, you need to remove numbers from the dataframe, use below:</p> <pre><code>df_new=df.replace('\d+ ','',regex=True) print(df_new) id descriptions 0 0 kartu debit indomaretcipete r 1 1 tarikan atm 10 2 2 tarikan atm 10 3 3 biaya a...
python|regex|pandas|dataframe
3
357,018
54,325,739
Showing the total of a column without repeating values
<p>I have a script which outputs a csv with five columns. I've added two lines of code to SUM two of those columns. I have managed to do this, however, the totals are these columns are repeated on every row, where i just want the totals to be shown on one row.</p> <pre><code>df['Unit Total'] = df['Units Sold'].sum() d...
<p>Set first value of index by position:</p> <pre><code>df.loc[df.index[0], 'Unit Total'] = df['Units Sold'].sum() df.loc[df.index[0], 'Unit Revenue'] = df['data_revenue'].sum() </code></pre> <p>Another solution is create default index by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFram...
python|pandas
1
357,019
54,471,121
Replace zero with the previous non-zero value
<p>I have an indicator variable in my dataframe that takes on the values 1 0 or -1. I'd like to create a new variable that avoids the 0's and instead repeats the nonzero values of the indicator variable until it changes to 1 or -1. </p> <p>I tried various constructions using the np.where statement, but I cannot solve ...
<p>Use <code>mask</code> and <code>ffill</code>:</p> <pre><code>df['Ind'].mask(df['Ind'] == 0).ffill() 0 1.0 1 1.0 2 1.0 3 -1.0 4 -1.0 5 -1.0 6 -1.0 7 1.0 8 1.0 9 1.0 Name: Ind, dtype: float64 </code></pre> <hr> <pre><code>df['Ind'].mask(df['Ind'] == 0).ffill(downcast='infer') 0 1 1 ...
python|pandas|if-statement
3
357,020
54,681,484
Counting the repeated values in one column base on other column
<p>Using Panda, I am dealing with the following CSV data type:</p> <pre><code>f,f,f,f,f,t,f,f,f,t,f,t,g,f,n,f,f,t,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,t,t,t,nowin t,f,f,f,f,f,f,f,f,f,t,f,g,f,b,f,f,t,f,f,f,f,f,t,f,t,f,f,f,f,f,f,f,t,f,n,won t,f,f,f,t,f,f,f,t,f,t,f,g,f,b,f,f,t,f,f,f,t,f,t,f,t,f,f,f,f,f,f,f,t,f,n,won f,f,f,f,f,f...
<p>This could work - </p> <p><code>outdf = df.apply(lambda x: pd.crosstab(index=df.target,columns=x).to_dict())</code></p> <p>Basically we are going in on each feature column and making a crosstab with target column</p> <p><a href="https://i.stack.imgur.com/mN5OA.png" rel="nofollow noreferrer"><img src="https://i.st...
python|pandas
1
357,021
54,542,757
No gradients provided for any variable, Tensorflow Linear Regression
<p>I'm currently learning how to use Tensorflow and I'm having some issues with this code for a Linear Regression aplication.</p> <p>Here is the full error description:</p> <blockquote> <p>ValueError: No gradients provided for any variable, check your graph for ops that do not support gradients, between variables [...
<p>Here is a working example of your code:</p> <pre><code>import tensorflow as tf import numpy as np import matplotlib.pyplot as plt num_points = 200 a = 0.22 b = 0.78 # No need to create everything in a loop, np.random.normal takes a size parameter x_points = np.random.normal(0.0, 0.5, 200) y_points = a*x_points + b...
python|tensorflow|machine-learning
0
357,022
54,263,740
How to parse nested table from HTML link using BeautifulSoup in Python?
<p>All,</p> <p>I am trying to Parse table from this link <a href="http://web1.ncaa.org/stats/StatsSrv/careersearch" rel="nofollow noreferrer">http://web1.ncaa.org/stats/StatsSrv/careersearch</a>. Please Note: For searching under "School/Sport Search" select All for School, Year -2005-2006, Sport -Football, Division ...
<blockquote> <p>My question is Is something like this possible ?</p> </blockquote> <p>Yes.</p> <blockquote> <p>If yes,how ?</p> </blockquote> <p>There is a lot going in the code below. But the main point is to figure out the post requests being made by the browser and then emulate that using Requests. We can find out t...
python-3.x|pandas|beautifulsoup|html-parsing|html-parser
1
357,023
54,559,649
Reshaping pandas multi-index dataframe to multi-column
<p>i have been trying to reshape a given pandas dataframe for two days. I would like to transform my multi-index dataframe into multi-column form, but failed greatly by using pd.stack(), pd.unstack(), pd.melt(), ... </p> <p>I have a generic multi-index dataframe, given as:</p> <pre><code>import pandas df = pandas.Da...
<p>There are many good answers on melt and pivot on SO. In your sample df, sum column is of string type. Convert it to int and use pivot_table. Key difference between pivot and pivot_table is that when your index contains duplicated entries, you need to use pivot_table with some aggregate function. If you don't pass an...
python|pandas|multiple-columns|multi-index
4
357,024
54,635,157
How should Euler integration be implemented in TensorFlow?
<p>I want to write a crude Euler simulation of a set of PDEs. I read the <a href="https://www.tensorflow.org/tutorials/non-ml/pdes" rel="nofollow noreferrer">PDE tutorial on tensorflow.org</a> and I am a little puzzled about how to do this properly. I have two specific questions but would welcome further feedback if th...
<p>Indeed, you can make sure that things run in the order that you want using <a href="https://www.tensorflow.org/api_docs/python/tf/control_dependencies" rel="nofollow noreferrer">control dependencies</a>. In this case, you just need to make sure that <code>U_</code> and <code>Ut_</code> are computed before the assign...
python|tensorflow|operator-precedence
0
357,025
54,643,951
How to combine array columns which have Nan values?
<p>i'm a beginner in python and I have some problems with combining data.</p> <p>What I want to do is deal with my data, completely discarding columns that have Nan values.</p> <p>But the indices of Nan values are different in most of my data.</p> <p>For example,</p> <pre><code>data1 = np.array([1, 2, np.nan, 4, 5]...
<pre><code>&gt;&gt;&gt; truth = ~np.isnan(data1) &amp; ~np.isnan(data2) &amp; ~np.isnan(data3) &gt;&gt;&gt; data1[truth] [4. 5.] &gt;&gt;&gt; data2[truth] [4. 5.] &gt;&gt;&gt; data3[truth] [4. 5.] </code></pre>
python|python-3.x|numpy
4
357,026
54,343,410
Pandas read csv column values as list
<p>I have a large dataframe with 6 columns, each with a list. When I save the dataframe to csv and read the csv, the lists are converted to strings. </p> <p>I found one question that was close to mine: <a href="https://stackoverflow.com/questions/32742976/how-to-read-a-column-of-csv-as-dtype-list-using-pandas">How to ...
<p>You can try using <code>pickle</code></p> <p><strong>Ex:</strong></p> <pre><code>import pandas as pd df = pd.DataFrame({"Col": [[1,2,3], [4,5,6]]}) df.to_pickle(filename) #Read the pickle file df = pd.read_pickle(filename) print(df["Col"]) print(df["Col"][0][0]) </code></pre> <p><strong>Output:</strong></p> <p...
python|pandas|csv
0
357,027
54,307,225
What's the difference between torch.stack() and torch.cat()?
<p>What's the difference between <a href="https://pytorch.org/docs/stable/generated/torch.cat.html" rel="noreferrer"><code>torch.cat</code></a> and <a href="https://pytorch.org/docs/stable/generated/torch.stack.html" rel="noreferrer"><code>torch.stack</code></a>?</p> <hr /> <p>OpenAI's <a href="https://github.com/pytor...
<p><a href="https://pytorch.org/docs/stable/generated/torch.stack.html" rel="noreferrer"><code>stack</code></a></p> <blockquote> <p>Concatenates sequence of tensors along a <strong>new dimension</strong>.</p> </blockquote> <p><a href="https://pytorch.org/docs/stable/generated/torch.cat.html" rel="noreferrer"><code>cat<...
python|pytorch
185
357,028
54,278,595
Extract part of a string with regex before hyphen followed by digits
<p>I have a dataframe <code>test</code> with a column <code>category</code> containing a complex pattern of words, characters and digits. I need to extract words separated by hyphen before another followed by digits into a new column <code>sub_category</code>.</p> <p>I'm not a regex expert and spent too much time figh...
<p>Use str.extract,</p> <pre><code>test['sub-category'] = test.category.str.extract('(.*)-\d+') id category sub-category 0 1 worda-wordb-1234.ds.er89. worda-wordb 1 2 worda-4567.we.77-ty worda 2 3 wordc-wordd-5698/de/ wordc-wordd 3 4 wordc-2356/rt/ ...
python|regex|python-3.x|pandas
2
357,029
54,489,299
How to fill missing values using values of closest neighboring years for a Pandas panel?
<p>For the following example, I would like to use the value of 1994. The SIC is usually the same across all the years. In rare cases, it could different across time. I have a big panel of 250K observations. Thank you!</p> <pre><code>Group Num Date SIC 100783 1994-03-28 2621 100783 1995-03-30 NaN 100783 1996-...
<p>I will extend and provide more guidance on the answer you have been given in the comments by Wen-Ben.</p> <p>First of all, for this to work you need an ordered DataFrame, based on <code>Group Num</code> and <code>Date</code> variables. If you are sure that your DataFrame has already been ordered, you don't need to ...
python|pandas
1
357,030
54,271,807
How to add a name to the columns of a dataframe in pandas
<p><a href="https://i.stack.imgur.com/xUtxs.png" rel="nofollow noreferrer">Sample underlined in red</a></p> <p>This is what I'm trying to achieve. Is there something similar to adding a name to the index or is this not possible?</p>
<p>I am considering a few rows and columns of your dataframe.</p> <p>Input:</p> <pre><code>df AA AS DAY_OF_WEEK 1 617 2129 2 9793 9723 3 4814 4814 </code></pre> <p>Just, do this </p> <pre><code>df.columns.name = 'AIRLINE' df </code></pre> <p>Output:</p>...
python|pandas|dataframe
1
357,031
54,654,943
Pandas two dataframes looking up IP's in CIDR's and mapping inCIDR column
<p>I have 2 dataframes. One(df1) with CIDR and a column that will always be one to enrich the second dataframe. The other dataframe(df2) has a list of ips. I would like to possibly iterate the IP's through the the CIDR's in df1 and label df2 if it is in one. I have read through the documentation for the libraries <co...
<p>If you need to map values based on first two values in ipaddress</p> <pre><code>new_df = df1.copy() new_df['CIDR'] = new_df['CIDR'].str.extract('(\d+.\d+).') df2['inCIDR'] = df2['ipaddress'].str.extract('(\d+.\d+).')[0].map(new_df.set_index('CIDR')['inCIDR']).fillna(0).astype(int) ipaddress inCIDR 0 1...
python|pandas
1
357,032
54,668,666
Howto force Pandas and native matplotlib to share axis
<p>I folks,</p> <p>Consider the following example</p> <pre><code>import matplotlib.pyplot as plt import pandas as pd import numpy as np fig, (ax1,ax2) = plt.subplots(2,1) dates = pd.date_range("2018-01-01","2019-01-01",freq = "1d") x = pd.DataFrame(index = dates, data = np.linspace(0,1,len(dates)) ) x.plot(ax=ax1) y...
<p>One way to do it would be to do all the plotting with matplotlib, this way there are no problems with the different time formats being used:</p> <pre><code>import matplotlib.pyplot as plt import pandas as pd import numpy as np fig, (ax1,ax2) = plt.subplots(2,1, sharex='col') dates = pd.date_range("2018-01-01","201...
python|pandas|matplotlib
3
357,033
54,258,626
How to save data from pandastable?
<p>I'm creating a table interface in which the user will receive a table from pandastable and write some data. Then, I need to save the updated pandastable to make some evaluations. How could I do this?</p> <p>This is the code:</p> <pre><code>from tkinter import * from pandastable import Table, TableModel import pand...
<p>You can use the following line:</p> <pre><code>pt.doExport(filename="test2.csv") </code></pre> <p>This will result in a .csv file with all of the data from the table.</p>
python|python-3.x|pandas|dataframe
2
357,034
54,369,443
I want to make a single dictionary from a dictionary of dictionary in python
<p>I have dictionary which contains dictionary as value for it's keys. I want to create a single dictionary out of it and also if there are keys repeating it should add the values of those keys</p> <p>So I have </p> <pre><code>temp_dict = {0: {'a':1, 'b':2}, 1: {'c':3,'d':4}, 2: {'d':5,'e':6}} </code></pre> <p>I tri...
<p>You can use <code>Counter</code> from the stdlib</p> <pre><code>from collections import Counter c = Counter() for i in temp_dict.values(): c.update(i) Counter({'a': 1, 'b': 2, 'c': 3, 'd': 9, 'e': 6}) </code></pre>
python|pandas|dictionary|merge|nested
0
357,035
54,452,340
No connection between any variable and the result of the loss function
<p>The optimizer I'm using isn't finding a connection between my variables and the loss function. </p> <p>I'm new to machine learning in general and I'm trying to build a curve fitting application for the equation y = a * 2^(t/b). The trainable variables being "a" and "b". Right now I'm testing it with some synthetic ...
<p>The optimizer tries to optimize a variable tensor created with <code>tf.variable</code> given the loss between the prediction and the expected value. You have to pass a prediction value as the following :</p> <pre class="lang-js prettyprint-override"><code>function predict(t) { // y = a * 2 ^ (t / b) return tf....
tensorflow.js
0
357,036
54,452,598
Jupyter: How can you pretty-print many data frames from the code in one cell?
<p>When you run a function that returns a Pandas data frame in a Jupyter cell, it prints out this very aesthetic table. When you give an explicit command to print, it looks much worse. I have a list of data frames and I'd like to print each. Is there a way to get the nice version of the print using a for-loop?</p>
<p>As mentioned in the comment, using <code>display</code> instead of <code>print</code> does the job.</p>
python|pandas|jupyter|pretty-print
2
357,037
54,263,287
Numpy is installed but still get the error "No module named numpy"
<p>I am trying to run a python script which needs <code>numpy</code> module ,when I try to install it,it shows it is already present, when I run <code>import numpy</code>it throws the error <code>ImportError: No module named numpy</code>,any guidance on what is wrong?</p> <pre><code>[username@machine build]$ pip insta...
<p>If you're running Linux then use <code>python2.7 -m pip install numpy</code></p>
python|numpy
0
357,038
54,653,778
How to set values of two columns in pandas
<p>I have a function which returns a tuple with two elements in python. I'm going to use this function to create two new columns in my dataframe in pandas. This is the code I have now</p> <pre><code>df['A','B'] = df.apply(lambda x: my_fun (X['A'], x['B'], other_arguments)[0:2], axis=1) </code></pre> <p><code>my_fun</...
<p>Try</p> <pre><code>df['A'], df['B'] = df.apply(lambda x: my_fun(x['A'], x['B'], other_arguments)[:2], axis=1) </code></pre> <p>if <code>my_fun</code> returns a tuple with 5 elements and you only want to keep the first 2, then use a slice with the function call <code>[:2]</code></p>
python|pandas
1
357,039
54,580,278
Why can't one set to "False" specific axis ticklabels (ex: xlabels_top, ylabels_right) from a cartopy-geopandas plot?
<p>I am having serious difficulties in setting to <code>False</code> the <code>xlabels_top</code> and <code>ylabels_right</code> from my Geopandas plot.</p> <p>This geopandas plot is made inside a <code>Geoaxes</code> subplot created with <code>PlateCarree</code> projection from Cartopy library.</p> <p>My geopandas <...
<p>The labels belong to the gridliner instance not the axes, you can turn them off there by storing the gridliner returned by the gridlines method and setting <code>top_labels</code>, <code>right_labels</code> as in:</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt import cartopy.crs...
python-3.x|matplotlib|geopandas|cartopy
2
357,040
54,567,734
How to add nested list as new column to existing pandas data-frame
<p>I have created a dataframe "df" which looks like this:</p> <pre><code> Name 0. School 1. Organisation 2. Teacher 3. Guest </code></pre> <p>now I have three lists </p> <pre><code>1. A = ['','','',['12','4']] 2. B = ['','','',['3','8']] 3. status = ['','','','[['yes','no','yes'],['no','yes','no']]] 4. letter = ...
<p>Can you try the following:</p> <pre><code>name = ['School', 'Organization', 'Teacher', 'Guest'] A = ['','','',['12','4']] B = ['','','',['3','8']] status = ['','','',[['yes','no','yes'],['no','yes','no']]] letter = [['', '', '', [[['K', 'L'], ['L'], ['L']], [['O'], ['P', 'O'], ['K']]]]] final_list = [] for a, b, c...
python|python-3.x|pandas|dataframe
4
357,041
54,611,144
TensorFlow object detection model works properly with stock model, but fails with error about an implemented operation not being implemented
<p>Using the TPU training mode on Google Cloud, I trained an SSD MobileNet V1 FPN model to recognize two types of objects. The model trained without errors, and I was able to evaluate in TensorBoard. Following conversion to TensorFlow Lite and attempting to run the model in the demo application for object detection, th...
<p>I found the solution to the issue. Using TensorFlow <code>v1.13.0-rc1</code> appears to resolve the issue at this point.</p> <p>This is because the <code>ResizeNearestNeighbor</code> operation for TensorFlow Lite did not exist until v1.13, and I realize that my main mistake was looking at the documentation for v1.1...
android|tensorflow|python-3.6|object-detection-api
0
357,042
54,422,946
Iterate through columns of an array to standardize data
<p>So I wrote a function to standardize my data but I'm having trouble making it work. I want to iterate through an array of my data and standardize it </p> <p>Here's my function</p> <p>I've tried Transposing my arr but it still doesn't work?</p> <pre><code>def Scaling(arr,data): scaled=[[]] for a in ...
<p>Because <code>data.mean()</code> and <code>data.std()</code> are aggregated constants or scalars, consider running the needed arithmetic operation <em>directly</em> on entire array without any <code>for</code> loops. Each constant will be operated on each column of array in a vectorized operation:</p> <pre><code>de...
python|arrays|numpy|for-loop
1
357,043
54,558,981
Looking for a sequential pattern with condition
<p>I have a df as </p> <pre><code> Id Event SeqNo 1 A 1 1 B 2 1 C 3 1 ABD 4 1 A 5 1 C 6 1 A 7 1 CDE 8 1 D 9 1 B 10 1 ABD 11 1 D 12 1 B 13 1 CDE 14 1 A 15 </code></pre> <p>I am looking for ...
<p>Here's a vectorized one with some scaling trickery and leveraging convolution to find the required pattern -</p> <pre><code># Get the col in context and scale it to the three strings to form an ID array a = df['Event'] id_ar = (a=='ABD') + 2*(a=='B') + 3*(a=='CDE') # Mask of those specific strings and hence extrac...
python|pandas|numpy|dataframe|data-manipulation
2
357,044
54,584,632
How to append string to each subsequent row in dataframe?
<p>Let's say I have a dataframe that looks like this:</p> <pre><code>REFERENCE_CODE dog 1 2 3 4 cat 1 2 4 5 rat 3 4 5 fish 4 5 6 </code></pre> <p>Notice the spaces.. I would like to achieve a dataframe that looks like this:</p> <pre><code>REFERENCE_CODE dog dog_1 dog_2 dog_3 dog_4 cat cat_1 cat_2 cat_4 cat_5 r...
<p>To get the groups you can use a mask and cumsum:</p> <pre><code>In [11]: headers = (df.REFERENCE_CODE != '') &amp; ~df.REFERENCE_CODE.str.isnumeric() In [12]: headers.cumsum() Out[12]: 0 1 1 1 2 1 3 1 4 1 5 2 6 2 7 2 8 2 9 2 10 2 11 2 12 3 13 3 14 3 15 3 16...
python|pandas
1
357,045
54,390,437
Using Pandas data frame assign values from one column to a variable using another variable for the column name
<p>In C# I'm sending in the following which is sys.argv<a href="https://i.stack.imgur.com/yDXdh.png" rel="nofollow noreferrer">1</a>:</p> <pre><code>string depVar = "Cover_Type"; </code></pre> <p>In Python I'm trying to accomplish the following using a Pandas data frame. The example code below fails...is there a way...
<p>Just go straight with</p> <pre><code>y = df['Flower_Type'] </code></pre> <p>Why does it have to be stored in a variable?</p>
python|pandas
0
357,046
73,614,535
tf_agents dqn fails to initialize
<p>Even though tf.agents initialize() require no input variables, this line</p> <pre><code>agent.initialize() </code></pre> <p>produces this error</p> <pre><code>TypeError: initialize() missing 1 required positional argument: 'self' </code></pre> <p>Ive tried agent.initialize(agent) because it apparently wanted self pa...
<p>I guess, answer is very simple: you can't just move <code>(</code> to the next line for the function call.</p> <p>What you're effectively doing:</p> <p>make <code>agent</code> an alias for <code>dqn_agent.DqnAgent</code> (the class)</p> <pre><code>agent = dqn_agent.DqnAgent </code></pre> <p>calculate an expression a...
python|tensorflow|dqn|tf-agent
1
357,047
73,665,275
How do I get the first and second closest datetime in date by a specific column?
<p>I need to create a new df that takes both the most recent date and the second most recent date for each store in the Date Time column; however, not all stores have a previous visit dates so some may need to return Nan.</p> <p>df</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Store</th> ...
<p>You can group the dataframe by <code>store</code>, then sort the Date Time values for each group, and take the most recent and second recent values for the timestamp:</p> <pre class="lang-py prettyprint-override"><code>( df .groupby('Store')['Date Time'] .agg(lambda x: dict(zip(['Most Recent Visit Date',...
python|pandas|datetime
0
357,048
73,671,862
NVIDIA vs PyTorch versions of cuDNN
<p>After installing PyTorch as per the official command: <code>conda install pytorch==1.7.1 torchvision==0.8.2 torchaudio==0.7.2 cudatoolkit=10.2 -c pytorch</code>, my cuDNN version shown in <code>conda list</code> is <code>pytorch 1.7.1 py3.8_cuda10.2.89_cudnn7.6.5_0 pytorch</code> whereas my system has <code>cudnn8.5...
<p><strong>TLDR</strong>; Probably no, but depends on the difference between versions.</p> <h2>Explanation</h2> <p>In reality upgrades (like what you have conda <code>cudnn7.6.5_0</code> -&gt; <code>cudnn8.5.0</code> of the system) usually don't harm training because versions are backward compatible for a while. After ...
pytorch|cudnn
0
357,049
73,636,833
Rename classes in bar plots unstacked from group by
<p>I would like to change labels to bar plots from <code>groupby</code>, possibly by mapping a label to classes instead of changing values in the dataset.</p> <p>In matplotlib it is possible to style the classes : <a href="https://www.pythoncharts.com/matplotlib/grouped-bar-charts-matplotlib/" rel="nofollow noreferrer"...
<p>You can just replace the data before plot:</p> <pre><code># crosstab is a bit slower than groupby().value_counts().unstack() # but it's more concise! pd.crosstab(dt['A'], dt['B'].replace({0:'good', 1:'OK', 2:'bad'})).plot.bar() </code></pre> <p>Output:</p> <p><a href="https://i.stack.imgur.com/N5fdY.png" rel="nofoll...
python|pandas|matplotlib|group-by|multi-index
0
357,050
73,650,441
Duplicate substring removal from list
<p>I have a dataframe with a product_type column that has duplicate substrings within strings:</p> <h3>df1</h3> <pre><code>product_type bag,bag tote bag,bag handbag,handbag </code></pre> <p>I'm using this line to remove to create a new column &quot;unique_type&quot; the duplicate substrings</p> <pre><code>df_1['unique...
<p>Add <code>join</code>:</p> <pre><code>df_1['unique_type'] = [', '.join(set(sub.split(','))) for sub in df_1[&quot;product_type&quot;]] </code></pre> <p>Or if need same order of values use <code>dict.fromkeys</code> trick:</p> <pre><code>df_1['unique_type1'] = [', '.join(dict.fromkeys(sub.split(','))) ...
python|pandas|list|dataframe
2
357,051
73,671,900
Error in Pandas using, miniconda, Jupyter notebook and python 3.7
<p>When i run covid = pd.read_csv('data.csv') using Jupyter, pandas and python 3.7, i get the following error:</p> <p>AttributeError Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_4552\740331431.py in ----&gt; 1 covid = pd.read_csv('data.csv')</p> <p>AttributeError: module ...
<p>You probably have a file named <code>pandas.py</code> that shadows the real module pandas/pd.</p> <p>Look up in your current directory (and/or your project directory) for this file and <strong>rename it</strong> to something other than these :</p> <pre><code>['BooleanDtype', 'Categorical', 'CategoricalDtype', 'Categ...
pandas
0
357,052
73,799,682
Extract strings based on custom list of items
<p>Say we have this df:</p> <pre><code>import pandas as pd df = pd.DataFrame({'a': ['hair color other family, friends ', 'family, friends hair color']}) a 0 hair color other family, friends 1 family, friends hair color </code></pre> <p>I want to extract strings using my own list of items:</p> <pre><code>items ...
<p>You can craft a regex to use with <a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.str.extractall.html" rel="nofollow noreferrer"><code>str.extractall</code></a>:</p> <pre><code>import re regex = '|'.join([f'({re.escape(i)})' for i in items]) # '(hair\\ color)|(other)|(family,\\ friends)' df.joi...
python|pandas|string
2
357,053
73,648,301
How to sort, group, and aggregate values in a list of nested dictionaries?
<p>given the list of dictionaries below, I want to do the following things:</p> <p>1: Sort the following data by key (top level)'name' <br /> 2: Sort the by the nested key &quot;name&quot; under key &quot;items&quot; <br /> 3: Group values under items by aggregation interval for example &quot;1d&quot; <br /> 4: Get aga...
<p>With the initial list of dicts that you provided and that I choose to call <code>data</code>, here is one way to do it:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame(data) # First, sort values df = df.assign(temp=df[&quot;items&quot;].apply(lambda x: x[0][&quot;name&quot;])).pipe( lambda...
python|pandas|dataframe|aggregation
1
357,054
73,554,882
Percentage with top 10 values in Python
<p>Need some help in getting top 10 values and percentages in Python. The Code I've already tried is given below:-</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns df=pd.read_csv('train_feature_store.csv') df.info df.head df.columns plt.figure(figsize=(20,6))...
<p>After doing this:</p> <pre><code>Size = df[['Size','Store']].groupby(['Store'], as_index=False).sum() </code></pre> <p>You can do the following:</p> <pre><code>df1 = Size.sort_values(by=['Size'],ascending=False).head(10).reset_index(drop=True) df1['Percentage'] = (df1['Size'] / df1['Size'].sum()) * 100 df1.loc[10,:]...
pandas|data-analysis|exploratory-data-analysis
0
357,055
73,602,730
Adding column by substring from another column in Pandas
<p>I have a data frame with one column,</p> <pre><code>DF = pd.DataFrame({'files': [&quot;S18-000344PAS&quot;, &quot;S18-001850HE1&quot;, &quot;S18-00344HE1&quot;]}) </code></pre> <p>I want to add another column with the substring of files, the final dataframe should look like</p> <pre><code>DF = pd.DataFrame({'files':...
<p>If you want to extract last 3 characters from the <code>files</code> column you can do:</p> <pre class="lang-py prettyprint-override"><code>DF[&quot;stain&quot;] = DF[&quot;files&quot;].str[-3:] print(DF) </code></pre> <p>Prints:</p> <pre><code> files stain 0 S18-000344PAS PAS 1 S18-001850HE1 HE1 2 ...
python|pandas
1
357,056
73,783,244
How to add day of the year column w.r.t Date in pandas
<p>I have a date column and I want to add the day of year(1-365), day of half year(1-182), day of quarter(1-92) and day of half quarter(1-46) columns to my dataframe w.r.t date.</p> <pre><code>In R we can use df$half_year = df$yearday %% 182 </code></pre> <p>Can anyone help me with this?</p>
<p>the pandas.Timestamp has a descriptor called <em>dayofyear</em> which you can call like this: <em>pd.Timestamp.dayofyear</em></p> <pre><code>import pandas as pd # create dates some_dates = pd.date_range( start=pd.to_datetime('07-02-1990', format='%m-%d-%Y'), end=pd.to_datetime('07-04-1990', format='%m-%d-%Y...
python|pandas|dataframe|date
2
357,057
73,787,150
updating only decimal with trailing zero
<p>How can we update only the decimal values of the column with trailing zeros if there are only one digit after decimal.</p> <p>Example dataframe:</p> <pre><code>df = pd.DataFrame(data=[[0.3, 0.3], [0.5, 1], [0.400, 0.4], [0.2, 5],[1.2, 1.55]], columns=['credit', 'min_credit']) </code></pre> <p>Executing the below...
<p>I would do it following way</p> <pre><code>import pandas as pd df = pd.DataFrame(data=[[0.3, 0.3], [0.5, 1], [0.400, 0.4], [0.2, 5],[1.2, 1.55]], columns=['credit', 'min_credit']) def stringify(x): return '{:.2f}'.format(x) if x%1 else '{:.0f}'.format(x) df['min_credit'] = df['min_credit'].apply(stringify) print...
python|pandas
2
357,058
73,776,870
Combine unnormalized key/value columns into normalized form
<p>I'm working on a legacy database with a table that looks like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Account</th> <th>Key1</th> <th>Key2</th> <th>Key3</th> <th>Val1</th> <th>Val2</th> <th>Val3</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Home</td> <td>Work</td> <td></td...
<p>You could use <a href="https://pandas.pydata.org/docs/reference/api/pandas.wide_to_long.html" rel="nofollow noreferrer">wide-to-long</a> for this</p> <pre><code>( pd.wide_to_long(df, ['Key','Val'], i='Account', j='n') .dropna() .reset_index() .drop(columns='n') ...
python|pandas|dataframe
5
357,059
73,767,843
improving fuzzy matching performance
<p>I have two data frames, the first one has 200k records and the second one has 9k. I need to apply fuzzy matching for string matching in two columns. I dropped the duplicate values in both data frames, but still, there might be similar strings. Hence, I wrote the below code. I thought that I can manually go through t...
<p>There is a package <a href="https://github.com/maxbachmann/rapidfuzz" rel="nofollow noreferrer">rapidfuzz</a> by <a href="https://stackoverflow.com/users/11335032/maxbachmann">@maxbachmann</a></p> <pre><code>pip install rapidfuzz </code></pre> <p>Sample usage:</p> <pre><code>from rapidfuzz import process, utils df['...
pandas|dataframe|performance|fuzzywuzzy
1
357,060
73,788,546
How to merge two dataframes without filling with NaN or zeros
<pre><code>frames = [df1, df2] result = pd.concat(frames) result.sample(n=5) </code></pre> <p>Two datasets have 4 columns and I would like to show them in one output, 8 columns together. The way I do is just filling with NaN. I just want to combine two separate tables.</p> <pre><code>df1 Column1 Column2 Column3...
<p>If both of your <code>DataFrame</code>s have the same index, you can perform <code>concat([…], axis=1</code> to horizontally stack your data.</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; pd.concat([df1, df2], axis=1) Column1 Column2 Column3 Column4 Column5 Column6 Column7 ...
python|pandas|dataframe|data-science
1
357,061
73,536,162
For each date - is it between any of the provided date bounds?
<h2>Data:</h2> <p><code>df</code>:</p> <pre><code> ts_code 2018-01-01 A 2018-02-07 A 2018-03-11 A 2022-07-08 A </code></pre> <p><code>df_cal</code>:</p> <pre><code>start_date end_date 2018-02-07 2018-03-12 2018-10-22 2018-11-16 2019-01-07 2019-03-08 2019-03-11 2019-04-22 2019-05-24 2019...
<p>You check with <code>numpy</code> broadcasting</p> <pre><code>df2['new'] = np.any((df1.end_date.values &gt;=df2.index.values[:,None])&amp; (df1.start_date.values &lt;= df2.index.values[:,None]),1).astype(int) df2 Out[55]: ts_code col new 2018-01-01 A 0 0 2018-02-07 ...
python|pandas|dataframe|datetime
3
357,062
73,733,024
sklearn "linear" unresolved reference
<p>I am trying to learn how to use sklearn, TF, pandas within pycharm. I was able to successfully import the above mentioned libraries and test the code to make sure they are functioning by printing the accuracy after train and test. All of the other capabilities inside of sklearn work without issue including <em>linea...
<p>For attributes such as .coef_ and .intercept_ .predict, these you need to go about by writing model.predict() / model.coef_ and so on. Could you give this a try?</p> <pre><code>model = linear_model.LinearRegression() model.fit(...) model.coef_ model.intercept_ model.predict(x_test) </code></pre> <p>should help solve...
python|tensorflow|sklearn-pandas
-2
357,063
73,736,786
How to select a subset of pandas dataframe containing an even distribution of one column's values?
<p>I have a huge dataset over different years. As a subsample for local tests, I need to separate a small dataframe which contains only a few samples distributed over years. Does anyone have any idea how to do that?</p> <p>After groupby by 'year' column, the count of instances in each year is something like:</p> <div c...
<p>Try <a href="https://numpy.org/doc/stable/reference/random/generated/numpy.random.randint.html" rel="nofollow noreferrer"><code>groupby().sample()</code></a>.</p> <p>Here's example usage with dummy data.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd # create a long arra...
pandas|dataframe
1
357,064
73,575,004
How to calculate centered moving mean (i.e., matlabs 'movmean') in python using numpy or scipy?
<p>I want to create a function identical to matlabs <a href="https://www.mathworks.com/help/matlab/ref/movmean.html" rel="nofollow noreferrer">movmean</a> function, whereby a sliding window moves through each datapoint in a list/array, and creates a new datapoint based on the average of its neighbors (centered on the c...
<p>Such function already exists in scipy and numpy libraries, probably should look at similar question answered <a href="https://stackoverflow.com/questions/13728392/moving-average-or-running-mean/22621523#22621523">here</a>.</p> <p>Would recommend to check out the source code of the functions and compare to your imple...
python|numpy|average
0
357,065
73,756,526
Merging two payroll reports in Python/Pandas and then producing columns comparing variances from month to month
<p><strong>Short version:</strong> I am merging two Excel payroll files to compare this month to the previous month. I want to add a third column that outputs the variance. I'd also like a separate report that excludes numbers that haven't changed from last month. Can anyone help with either?</p> <p><strong>Longer vers...
<p>This is a good use case for MultiIndex.</p> <ul> <li>For your first question, use <code>pd.concat</code>. <code>pd.concat([df1, df2, df3, ...], axis=1)</code> is same as <code>merge</code> but it only aligns on the index. You can optionally specify the <code>keys</code> which turns the resulting dataframe into a mul...
python|excel|pandas
0
357,066
73,746,488
Python find first occurrence in Pandas dataframe column 2 below threshold and return column 1 value same row using NumPy
<p>I have a dataframe as below:</p> <pre><code>0.1 0.65 0.2 0.664 0.3 0.606 0.4 0.587 0.5 0.602 0.6 0.59 0.7 0.53 </code></pre> <p>I have to find the first occurence below <strong>0.6</strong> in column 2 and return the value of the column 1 on same row. In that example the returned value would be <strong...
<p>You can use masking and the <code>df.head()</code> function to get the first occurrence given the threshold.</p> <pre><code>df[df[1] &lt; threshold].head(1)[0] 3 0.4 Name: 0, dtype: float64 </code></pre> <h2>Update</h2> <p>To use numpy, you need to convert the pandas to numpy and use <code>np.where</code>.</p> <...
python|pandas|dataframe|numpy|scipy
1
357,067
73,763,130
Concatenate a a string and integer to make a new column for each dataframe in a list of dataframes
<p>I want to make a new column for each dataframe in a list of dataframes called &quot;RING&quot; which contains the word &quot;RING&quot; + the another column called &quot;No&quot;.</p> <p>here is my solution so far</p> <pre><code>df_all = [df1,df2,df3] for df in df_all: df[&quot;RING &quot;] = &quot;RING&quot; +...
<p>You are almost there:</p> <pre><code>df_all = [df1,df2,df3] for df in df_all: df[&quot;RING&quot;] = &quot;RING&quot; + df[&quot;No&quot;] # If df[&quot;No&quot;] is not of type string, cast it to string: # df[&quot;RING&quot;] = &quot;RING&quot; + df[&quot;No&quot;].astype(&quot;str&quot;) df...
python|pandas|list|dataframe
1
357,068
73,559,986
Very simple pandas column/row transform that I cannot figure out
<p>I need to do a simple calculation on values in a dataframe, but I need some column transposed first. Once they are transposed I want to take the most recent amount / 2nd most recent amount and then the binary result if it less than or equal to .5</p> <p>By most recent I mean most recent to the date in the Date 2 col...
<p>This is the original dataframe.</p> <pre><code>df = pd.DataFrame({'Name':['Jim','Jim','Jim','Bob','Bob','Bob'], 'Amount':[100,200,150,350,300,400], 'Date 1':['2021-06-10','2021-05-11','2021-03-05','2022-06-10','2022-08-12','2021-07-06'], 'Date 2':['2021-06-15','2021-06-15...
python|python-3.x|pandas|dataframe
2
357,069
73,832,129
Nan values in columns when creating a dataframe
<p>I try to create a dataframe with columns. I import values of these columns from other dataframe that are not empty. But when i create it,, i get an empty dataframe with Nan VAlues .</p> <p>Here the code :</p> <pre><code># initialize data of lists. comparaison = {'actual': imp_all['prix_moyen'].tail(100), 'pr...
<p>The reason is that you try to assign an index to the series <code>actual</code> and <code>predicted</code> which apparently don't have datetime index. Try to alter the index after defining the new dataframe:</p> <pre><code>df = pd.DataFrame(comparaison) df.index = pd.date_range(start='2022-08-25', periods=100) </cod...
python|pandas|dataframe
1
357,070
73,690,748
Sklearn predict using a subset of my data
<p>Is there a way to use predict on a selection of rows from a pandas dataset? As an example:</p> <pre><code>from sklearn.ensemble import RandomForestClassifier clf = RandomForestClassifier() clf.fit(X, y) selection = [True, True, False, False, True, False] data = pd.DataFrame.from_dict( { &quot;A&quot;: ...
<p>You can try something like this:</p> <pre><code>data[&quot;selection&quot;] = selection selected_cols = data.columns[:-1] def predict(x): if x.selection: return (&quot;model.predict(x[selected_cols])&quot;) # call your model here else: return np.NAN data.apply(predict, axis=1) 0 model....
python|pandas|scikit-learn
0
357,071
73,802,333
Empty pivot table with pandas data frames
<p>I have <a href="https://stackoverflow.com/questions/56672506/missing-values-in-pandas-pivot-table">checked</a> <a href="https://stackoverflow.com/questions/26431157/python-pandas-pivot-table-missing-column-after-pivot">around</a>, but it seems I can't find this <a href="https://stackoverflow.com/questions/57548077/p...
<pre><code>pivot = pd.pivot(data, values='D', index=['A', 'B', 'C', 'E'], columns=['col']) </code></pre> <p>If you want to reset the index you can use <code>pivot.reset_index()</code> which returns:</p> <pre><code>col A B C E 10 0 a1 NaN c1 e1 0 1 a1 NaN c1 e2 0 2 a1 NaN c1 e3 0 3 ...
python|pandas|dataframe|pivot-table
1
357,072
73,645,103
df.to_sql error : 'h' format requires -32768 <= number <= 32767
<p>I am trying to ingest a dataframe to postgres db using python script in AWS Glue. It processes some dataframes, but for some dataframes, while doing <code>df.to_sql</code> it gives</p> <pre><code>'h' format requires -32768 &lt;= number &lt;= 32767 </code></pre> <p>If someone has experience with such kind of error, i...
<p>'h' is stored with a <a href="https://www.postgresql.org/docs/current/datatype-numeric.html" rel="nofollow noreferrer"><em>smallint</em> on 2 bytes</a> (-32768 to +32767).</p> <p>You must ensure that the column holding your hours are within those bounds.</p> <p>If you originally have integers, you can use <a href="h...
python|pandas|sqlalchemy
0
357,073
73,577,806
Join 2 datasets that have different levels
<p>I want to join two dataframes, but one of them is multi-indexed like so:</p> <p><a href="https://i.stack.imgur.com/FUvgL.png" rel="nofollow noreferrer">Multi-level dataframe</a></p> <p>The other dataframe is much simpler:</p> <p><a href="https://i.stack.imgur.com/2z4BB.png" rel="nofollow noreferrer">Basic dataframe<...
<p>There is several solution to your problem. I think you can use concat or merge from panda library. I hope it will help you:</p> <pre><code>import panda as pd dataframe1 = (pd.read_csv('test1.csv', sep=';', header=0, index_col=0, parse_dates=True, squeeze=True)) dataframe2 = (pd.read_csv('test2.csv', sep=';', header...
python|pandas|dataframe
0
357,074
73,656,205
How to compare specific cell within a specific range of row in Python?
<p>I need to compare two rows of column 1 (title) to see if they have the same content in an Excel file. Eg: rows 1, 2, 5, 6. If the row is the same, we can go to compare the two rows of column 2 (pc) if they have the same content. So how should I implement my code to get it working?</p> <pre><code> title pc rd/w...
<p>This is my df</p> <pre><code>title pc rd/wr Min Max Avg Std_dev 0 Test_1 PC0 Write 88 1838 634 297 1 Test_1 PC1 Write 92 2363 661 369 2 Test_2 PC0 Write 90 1524 576 273 3 Test_2 PC1 Write 94 1526 568 267 4 Test_1 PC0 Write 90 1850 623 287 5 Test_1 PC1 Write 89 ...
python|excel|pandas
0
357,075
73,827,456
Optimising finding the index of the highest value in a list
<p>I have a long list of machine learning prediction probabilities for multiple classes and I'm trying to find the highest probability for each prediction. I've implemented the method below for this and it works but it is taking a long time (~10 mins for this step alone) when applied to our typical dataset of order 100...
<p>You can use <code>np.argmax</code> and set <code>axis=1</code> to get <code>array([0, 0, 0])</code></p> <pre><code>import numpy as np predictions = np.array([[9.9696952e-01, 1.9961601e-06, 1.1957183e-03, 2.4479270e-05, 1.8083032e-03], [9.9696952e-01, 1.9961601e-06, 1.1957183e-03, 2.4479270e-...
python|list|numpy|xgboost|argmax
0
357,076
73,669,233
How to calculate YTD (Year to Date) value using Pandas Dataframe?
<p>I want to calculate <code>YTD</code> using pandas dataframe in each month. Here I have used two measurements named <code>sales</code> and <code>sales Rate</code>. For measurement <code>sales</code>, <code>YTD</code> is calculated by taking the cumulative sum.Code is given below:</p> <pre><code>report_table['ytd_valu...
<p>I recommend you change your dataframe around a bit:</p> <pre><code> Month Year Financial_Year Place Market Product Sales Sales Rate 0 April 2022 2023 Delhi Domestic Biscuit 10.0 10.0 1 May 2022 2023 Delhi Domestic Biscuit 10.0 20.0 2 June 2022 ...
python-3.x|pandas|dataframe
0
357,077
73,719,143
Create function to to detect dictionary types and extract the keys and values
<p>I have been given a dataframe that includes dictionaries and nested dictionaries.</p> <p>See here the examples and the different types of dictionaries one will find: type 1 (test_dict_1), type 2 (test_dict_2):</p> <pre><code>test_dict_1={'results': [{'key': 'q1', 'value': ['1'], 'end_time': '2021-01-21', 's...
<p>By far not the prettiest solution, but this works for my messy dataframe:</p> <pre><code>def recursive_items(dictionary): for key, value in dictionary.items(): if type(value) is dict: yield from recursive_items(value) else: yield (key, value) def extract_keys_values(df): for i in range(l...
python|pandas|dataframe|dictionary|key-value
0
357,078
73,678,304
Is there a way to show more columns per row from FastF1 (see code)
<p>I am very new to coding and I'm trying to view data from FastF1. I am attempting to do this using Python and Jupyter Lab. Whenever I print two columns using the code below:</p> <pre><code>import fastf1 from fastf1 import plotting import pandas as pd plotting.setup_mpl() pd.set_option('display.max_rows', None) pd.s...
<p>You can do dataframe subsetting like <code>fp3_d1[['LapTime', 'LapNumber']]</code>. This will output a subset of the dataframe with the 2 columns indicated.</p> <p>Refer to <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html" rel="nofollow noreferrer">pandas documentation</a> for more deta...
python|pandas|dataframe|jupyter-lab
3
357,079
73,620,947
How to append/concat second row with the first row within the similar dataframe in pandas
<p>I have a dataframe</p> <pre><code> 0 1 2 3 ............ 1041 1042 1043 0 32.5 19.4 66.6 91.4 55.5 10.4 77.2 1 13.3 85.3 22.4 65.8 23.4 90.2 14.5 2 22.4 91.7 57.1 23.5 58.2 81.5 46.7 3 75.7 47.1 ...
<p>Some manipulation of the column names and a trick with indexes is needed but sure it can be done. Remember to pay attention to the behavior when the number of columns is odd.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd # Create dummy data df = pd.DataFrame(np.random.ra...
python|pandas
0
357,080
73,612,307
pandas groupby multiple columns
<p>I have this pandas groupby command. I am not sure how to split the same groupby to get all the result. If i add another column say &quot;Name&quot;, it crashes or take forever to get the result back. I couldn't figure how to split the groupby.</p> <p>Please bear with me. I am new to pandas.</p> <pre><code>for x in...
<p>If I understand correctly, use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html" rel="nofollow noreferrer"><strong><code>pandas.DataFrame.sort_values</code></strong></a> instead of doing a groupby:</p> <pre><code>mylist = ['Name', 'Owner_Type','Year','Transmission...
pandas
0
357,081
73,768,312
Replace the dataframe entries with binary value
<p>Trying to replace certain strings with a binary value. I tried to find and replace but it only works for one value. I'd like to do it for multiple different labels. I'd like to replace dog and bat with 1 and cat and snail with 0 :</p> <pre><code>animal 0 cat 1 dog 2 snail 3 bat 4 deer </code></pre> <p>To:</p> <pre...
<p>Your code almost works, just need a slight change.</p> <pre><code>df['animal'] = np.where(df['animal'].isin(cold), '0', '1') animal 0 0 1 1 2 0 3 1 4 0 </code></pre> <p>Or you could use the answer in the comment.</p> <pre><code>df['animal'] = (~df['animal'].isin(cold)).astype(int) </code>...
python|pandas|dataframe
1
357,082
71,184,810
Converting to datetime - ParserError: Unknown string format: 2022-02-17 7
<p>I have a pandas dataframe with some string values that have the hour of a date in one-digit format if the hour is smaller than 10, like this:</p> <pre><code>2022-02-17 7 </code></pre> <p>I now want to get this strings to datetime format but when applying</p> <pre><code>df['datetime'] = pd.to_datetime(df['datetime'],...
<p>Use:</p> <pre><code>df = pd.DataFrame({'datetime':['2022-02-17 7']}) df['datetime'] = df['datetime'].str.replace(' (\d{1})', ' 0\\1') df['datetime'] = pd.to_datetime(df['datetime'], format='%Y-%m-%d %H') </code></pre> <p>The result:</p> <p><a href="https://i.stack.imgur.com/ceDVE.png" rel="nofollow noreferrer"><img ...
pandas|datetime|error-handling
1
357,083
71,371,164
Extracting chosen information from URL results into a dataframe
<p>I would like to create a dataframe by pulling only certain information from this website.</p> <p><a href="https://www.stockrover.com/build/production/Research/tail.js?1644930560" rel="nofollow noreferrer">https://www.stockrover.com/build/production/Research/tail.js?1644930560</a></p> <p>I would like to pull all the ...
<p>Use regex to extract the details followed by <a href="https://docs.python.org/3/library/ast.html#ast.literal_eval" rel="nofollow noreferrer"><code>literal_eval</code></a> to convert string to python object</p> <pre><code>import re from ast import literal_eval import pandas as pd import requests url = &quot;https:/...
python|pandas
2
357,084
71,278,444
I have a problem with construct regular expression
<p>I have a data frame where row in one column looks like this:</p> <pre><code>&lt;title&gt;Some text&lt;/title&gt; &lt;selftext&gt;Some text&lt;/selftext&gt; </code></pre> <p>This above is one row in one column. The problem is that not every row looks like this. I have to implement that rows which not looks like this...
<p>My first idea for what is wrong with the pattern would be that you set a range but only allow <em>exactly</em> one character. Use this to allow any content within title and selftext tags which have <em>at least</em> one character.</p> <pre><code>pattern = &quot;&lt;title&gt;[a-zA-Z0-9]+&lt;/title&gt;\n\n&lt;selftext...
python|pandas|python-re
1
357,085
71,373,344
Pandas get_dummies Join causes columns overlap
<p>I have the following code which joins <code>get_dummies</code> results:</p> <pre><code>mobile_companies = self.df[&quot;cell_phone&quot;].str.get_dummies(sep=&quot;、&quot;).astype(bool) self.df = self.df.join(mobile_companies) </code></pre> <p>which arise the following error:</p> <pre><code>raise ValueError(f&quot;c...
<p>Either <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.drop.html" rel="nofollow noreferrer"><code>drop</code></a> your column in the original DataFrame:</p> <pre><code>mobile_companies = self.df[&quot;cell_phone&quot;].str.get_dummies(sep=&quot;、&quot;).astype(bool) self.df = self.df.drop('au'...
pandas
0
357,086
71,231,290
Unable to use tf.while_loop properly
<p>My code :</p> <pre><code>def entropy(x): return tf.convert_to_tensor(skimage.measure_shannon_entropy(np.array(x))) </code></pre> <pre><code>def calc_entropy(x, fn): i = tf.constant(0) while_condition = lambda i: tf.less(i, fn) #loop r = tf.while_loop(while_condition, entropy, x[0, :, :, i]) return r </co...
<p>Try something like this:</p> <pre><code>import tensorflow as tf from skimage.measure.entropy import shannon_entropy import numpy as np def entropy(i, v, x): v = tf.tensor_scatter_nd_update(v, [[i]], [tf.convert_to_tensor(shannon_entropy(np.array(x[0, :, :, i])))]) return tf.add(i, 1), v, x def calc_entropy(x, ...
python|tensorflow|keras
1
357,087
71,140,874
How to get 2 data frames matched based on relation between two columns of the two dataframe
<p>I have two dataframes with data in the form of</p> <pre><code>Date Col1 Col2 Col3 1/1/2021 a b c 2/1/2021 d e f 3/1/2021 g h 1 Date Col4 Col5 Col6 1/1/2021 a b c 2/1/2021 d e f 3/1/2021 g h i </code></pre> <p>I have a relation that says</p> <pre><code>Cola Colb Col1 C...
<p>You could convert the <code>mapper_df</code>:</p> <pre><code>Cola Colb 0 Col1 Col4 1 Col2 Col5 2 Col3 Col6 </code></pre> <p>to a dictionary and modify the column names of <code>df2</code>. Then <code>stack</code> the DataFrames and <code>join</code> on &quot;Date&quot;:</p> <pre><code>d = mapper_df...
python|pandas|dataframe|data-preprocessing
1
357,088
71,213,320
Pandas how to do group by properly over certain conditions
<p>I had an issue when trying to group by in pandas, my data is this table until &quot;sum&quot; series, my desired output is some kind of group by that delivers me the results with these series: desired_clientgroup and DesiredGroup_out_sum/avg/max. For example the number &quot;104,23&quot; is the sum over the clientgr...
<p>IIUC, you could use:</p> <pre><code># start groups on 1 mask = df['client_items'].eq(1) df['clientgroup'] = mask.cumsum() # get the sum per group # assign result only on first group row df.loc[mask, 'output_sum'] = (df.groupby('clientgroup') ['sum'].transform('sum') ...
python|pandas|group-by
0
357,089
71,177,345
Keep only last six months data in Python Pandas dataframe
<p><code>from dateutil.relativedelta import relativedelta</code></p> <p>I did</p> <p><code>df['Date'] = pd.to_datetime(df['Date'])</code><br /> <code>six_months = date.today() - relativedelta( months = +6)</code><br /> <code>df = df.loc[(df['Date'] &gt;= six_months)]</code></p> <p>I kept getting following error <code>...
<p>Try this code</p> <pre><code>df['Date'].last('6M') </code></pre>
python|pandas|python-datetime
0
357,090
71,151,040
What are some ways I can structure this Semi-Structured dataframe from ndjson format?
<p>(This is not real data)</p> <p>I requested similar data from a Rest API. Then, I was able to convert some of the data to a .ndJSON format ( lines = True ); however, the address column is still shown in the ndjson format structure similar to a Python dictionary. My goal is to have the following columns: Column 1 | St...
<pre><code>import pandas as pd # dummy df df = pd.DataFrame({'address': [{'city': 'MURFREESBORO', 'line': ['9999 Candy Cane Island'], 'postalCode': '39999', 'state': '56'}], 'birthdate': ['11/20/1977']}) # remove the [] from our address colum df['address'] = df['address'].apply(str).str...
python|json|pandas|python-requests|ndjson
1
357,091
71,219,835
Pandas merging/joining tables with multiple key columns and duplicating rows where necessary
<p>I have several tables that contain lab results, with a 'master' table of sample data with things like a description. The results tables are also broken down by specimen (sub-samples). They contain multiple results columns - I'm just showing one here. I want to combine all the results tables into one dataframe, like ...
<p>First idea is join <code>df2, df3</code> together by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>concat</code></a> and for unique <code>'Location','Sample','Specimen'</code> rows are rows aggregated by <code>sum</code>, last merge to <code>df...
python|pandas
1
357,092
71,271,074
Conv2D is incompatible with the layer in a GAN
<p>I am developing a GAN using the Mnist dataset. I have developed the Generator and Discriminator. However, when I combine them together I get this error: <code>Input 0 of layer &quot;conv2d&quot; is incompatible with the layer: expected axis -1 of input shape to have value 1, but received input with shape (None, 57, ...
<p>Your generator needs to produce images, thus the output shape of the generator must be the same shape as the images. The activation also must be compatible with the range in the images. I don't think your images go from -1 to +1, so you should not use &quot;tanh&quot;. You must choose an activation compatible with t...
tensorflow|machine-learning|keras|deep-learning|generative-adversarial-network
1
357,093
71,229,600
How to merge next rows' start with current rows' end in Python
<p>For example if I have a DataFrame that looks like this</p> <p><a href="https://i.stack.imgur.com/Ttkkk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ttkkk.png" alt="enter image description here" /></a></p> <p>For the same id and Category, I would like to keep only the first start and last end nu...
<p>You could use <code>groupby</code> + <code>agg</code> where you call <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.GroupBy.first.html" rel="nofollow noreferrer"><code>first</code></a> on &quot;start&quot; and <a href="https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.GroupB...
python|pandas|dataframe|pandas-groupby|data-manipulation
1
357,094
71,349,844
removing just one of double indexes
<p>Is given a <em>pandas.core.series.Series</em> consisting of two <em>pandas.core.series.Series:</em></p> <pre><code>S1 = pd.concat([S,S]) e.g.:|index| value | | --- | -------- | |4707 | 25.408939| |13292| 24.288939| |38063| 22.766040| |39458|-16.478080| |39571|-15.085605| **|4707...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with <code>|</code> for bitwise <code>OR</code> with mask by <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.duplicated.html"...
python|pandas|duplicates|series
0
357,095
71,160,647
Pandas DataFrame Cross-Reference/Selective Join/Overlay?
<p>What is the best/fastest way to do a selective lookup/cross-reference/overlay/partial join between two Pandas DataFrames? I'm not sure of the right terminology to use....</p> <p>Given:</p> <ol> <li>A primary table filled with numerical values and some arbitrary lookup/reference strings, indexed by date/month</li> <l...
<p>One easy way is using replace , not sure about the speed</p> <pre><code>out = tb1.set_index('dte').T.replace(tb2.set_index('dte').T).T Out[172]: value1 value2 dte 2022-01 1 2 2022-02 3 102 2022-03 111 4 2022-04 5 6 </code></pre>
python|pandas|dataframe|data-science
1
357,096
71,219,153
Pivot wider to longer with value and unit (currency) columns
<p>My data is in wide format as such:</p> <pre><code>data = [{ id: '1', 'timestamp': '2021-10-01', 'product_type' : 'Quarterly', 'applicable_tariff_per_local_currency_kwh_d_value' : 1.11, 'applicable_tariff_per_local_currency_kwh_d_unit' : 'CZK/(kWh/d)/q', 'applicable_tariff_per_local_currency_kwh_h_value' : 11.11, 'a...
<p>Because you require two related columns (<code>value</code>, <code>unit</code>) in the output, you need to run <code>melt</code> twice:</p> <pre><code>In : d1 = pd.melt( ...: df, ...: id_vars=[&quot;id&quot;], ...: value_vars=[ ...: &quot;applicable_tariff_per_local_currency_k...
python|pandas|pandas-melt
0
357,097
71,157,737
Object detection evaluation model main error
<p>I'm currently working ona object detection model efficientnet and i tried to evaluate my mode with model main but got the error</p> <p>ValueError: Tensor(&quot;Detections_Left_Groundtruth_Right/0:0&quot;, shape=(), dtype=string) must be from the same graph as Tensor(&quot;Loss/TargetAssignment/AvgNumGroundtruthBoxes...
<p>You can fix it by passing the checkpoint file path correctly, e.g.: <code>--checkpoint_dir=/checkpoint/ckpt-x</code>, where x is the checkpoint number. Also check for this bug <a href="https://github.com/tensorflow/models/pull/5450" rel="nofollow noreferrer">https://github.com/tensorflow/models/pull/5450</a>. It wor...
python|tensorflow|object-detection
0
357,098
71,395,716
Add to a Pandas DafaFrame, information from another DataFrame & in the right order
<p>I have a Pandas dataframe like this :</p> <pre class="lang-py prettyprint-override"><code># FIRST DF ROW_A ROW_B a 52 a 52 b 45 b 45 b 45 c 69 </code></pre> <p>In a second dataframe :</p> <pre class="lang-py prettyprint-override"><code># SECOND DF ROW_A ROW_B ROW_C ...
<p>Use <code>df.merge</code> with <code>df.drop_duplicates</code>:</p> <pre><code>In [2113]: output = df1.merge(df2).drop_duplicates() In [2114]: output Out[2114]: ROW_A ROW_B ROW_C ROW_D 0 a 52 toto tata 1 a 52 titi tutu 4 b 45 hey hi 5 b 45 hola yo 6 b 4...
python|pandas|dataframe
3
357,099
71,398,383
Splitting a pandas dataframe by Dates
<p>I would like to create a pandas datasheet that gets the dictionary <code>a</code> below and adds <code>days_split</code> amount of days from the initial date and creates a table. So for the dictionary below since the first date value is <code>2/4/2022 1:33:40 PM</code> I would like to add another 10 days into it whi...
<p>Use <code>pandas.Grouper</code></p> <pre><code>df.Date = pd.to_datetime(df.Date) df = df.set_index(&quot;Date&quot;) groups = df.groupby(pd.Grouper(freq=&quot;10D&quot;)) for x in groups: print(x[1].reset_index()) </code></pre>
python|pandas|database|dataframe|numpy
2