无法通过 pandas 在我的数据框中按一级分组 [英] not able to groupby by one level in My dataframe by pandas
问题描述
我正在导入一个 excel 文档并创建一个数据框 df3.我只想按 Name
分组.其他重复数据应反映如输出所示.
I am importing an excel document and creating a dataframe, df3. I want to group by only Name
. The other uplicate data should reflect as shown in the output.
Df3 =pd.read_excel('stats')
print (df3)
Name ID Month Shift
Jon 1 Feb A
Jon 1 Jan B
Jon 1 Mar C
Mike 1 Jan A
Mike 1 Jan B
Jon 1 Feb C
Jon 1 Jan A
需要输出:
我想以相同的格式输出如下所示,并将保存在 excel 中.请帮助我,因为我被困在这里.注意(月份必须是升序)
I want to have output like as below in the same format and will save in excel. Please help me on same as I'm stuck here. Note (Month must be ascending order)
将非常感谢您的帮助和支持.
Will be greatfull for help and support .
推荐答案
您可以这样做.
解决方案:
输入:
姓名、ID、月份、班次
Name,ID,Month,Shift
Jon,1,Feb,A
Jon,1,Feb,A
Jon,1,Jan,B
Jon,1,Jan,B
Jon,1,Mar,C
Jon,1,Mar,C
Mike,1,Jan,A
Mike,1,Jan,A
Mike,1,Jan,B
Mike,1,Jan,B
Jon,1,Feb,C
Jon,1,Feb,C
Jon,1,Jan,A
Jon,1,Jan,A
我已将您的文件输入设为 csv.
I have taken your file input as csv.
代码:
import pandas as pd
filePath="{YourFilePathForReadingcsv}"
df=pd.read_csv(filePath,sep=',')
df['MonthNumber']=pd.to_datetime(df['Month'],format='%b')
df.set_index(['Name','MonthNumber'],inplace=True)
df.sort_index(inplace=True)
df.to_excel("{filePath}\Jon.xlsx")
输出:请在编写时删除列 MonthNumber.
Output: Please remove column MonthNumber while writing it.
这篇关于无法通过 pandas 在我的数据框中按一级分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!