![](/img/trans.png)
[英]What is the best way to retain data for columns that can't be aggregated during a a groupby operation on a pandas dataframe?
[英]Renaming columns in pandas dataframe during groupby operation
我試圖重命名作為groupby&count操作的結果而獲得的列,如下所示:
dfa = df.groupby('Product_ID').Product_ID.count().rename(columns={0: "Product",1:"Sale_count"}).reset_index()
print(dfa[:1])
獲得的輸出是
Product_ID 0
0 P00000142 1130
列名不是我指定的。 所以我再次使用以下命令更改了它
dfa.columns =['product','sales']
print(dfa[:1])
product sales
0 P00000142 1130
然后我得到了預期的列名。 但是我相信它將在第一個方法dataframe.rename本身中獲得。 我做的第一個代碼段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.