简体   繁体   English

在groupby操作期间重命名pandas数据框中的列

[英]Renaming columns in pandas dataframe during groupby operation

I tried to rename the column that has been obtained as the result of groupby & count operation like below: 我试图重命名作为groupby&count操作的结果而获得的列,如下所示:

dfa = df.groupby('Product_ID').Product_ID.count().rename(columns={0: "Product",1:"Sale_count"}).reset_index()
print(dfa[:1])

the output obtained is 获得的输出是

 Product_ID     0
0  P00000142  1130

The column names are not what I specified. 列名不是我指定的。 So I changed it again using the below command 所以我再次使用以下命令更改了它

dfa.columns =['product','sales']
print(dfa[:1])

 product  sales
0  P00000142   1130

Then I got the expected column names. 然后我得到了预期的列名。 However I believe it shall be obtained during the first method dataframe.rename itself. 但是我相信它将在第一个方法dataframe.rename本身中获得。 What is wrong in the 1st code snippet dfa = df.groupby('Product_ID').Product_ID.count().rename(columns={0: "Product",1:"Sale_count"}).reset_index() that I did not get the expected output. 我做的第一个代码段dfa = df.groupby('Product_ID').Product_ID.count().rename(columns={0: "Product",1:"Sale_count"}).reset_index()有什么问题无法获得预期的输出。

如评论中所述,您需要:

df.groupby('Product_ID').size().reset_index(name='sales_count')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM