pandas 如何按月分组一列,并添加两个额外的列?

nszi6y05  于 2022-12-16  发布在  其他
关注(0)|答案(1)|浏览(94)

有问题的表的图像。当我复制到这里时,它没有保持格式。
https://drive.google.com/file/d/1JkBJeX2hrDgiFvN3e2pzvJtz_xhbWcw-/view?usp=sharing
我有当前的数据框架(df5)我试图按月分组的日期,并添加毛和净。最终目标是绘制的毛和净每月随着时间的推移表。
管理了这行几乎可以工作的代码。

per = df5.Date.dt.to_period("M")
g = df5.groupby(per)
df51 = g.sum() 
df51.drop(columns=['Qty', 'Price', 'Cost' ], inplace=True)
df51.head(30)

问题是日期列不在 Dataframe 中。

Gross   Net
Date        
2021-08 4351.50 1351.50
2021-09 6835.00 2035.00
2021-10 4828.00 1628.00
2021-11 5258.50 1608.50
2021-12 4618.00 1418.00
2022-01 6515.50 2015.50 
...

试过这个:

per = df5.Date.dt.to_period("M")
    g = df5.groupby(per)
    df51 = g.sum() 
    df51.drop(columns=['Qty', 'Price', 'Cost' ], inplace=True)
    df51.head(30)

预期:

Date    Gross   Net     
2021-08 4351.50 1351.50
2021-09 6835.00 2035.00
2021-10 4828.00 1628.00
2021-11 5258.50 1608.50
2021-12 4618.00 1418.00
2022-01 6515.50 2015.50
...

日期似乎在数据框之外,在调用标题等时不会显示。

shyt4zoc

shyt4zoc1#

我想这应该可以解决你的问题。你可以这样编辑1列。

df["date"] = df["date"].dt.to_period()
df = df.groupby(by=["per"]).sum()

相关问题