假设我有以下数据帧:
year count 2001 14 2004 16 2001 2 2005 21 2001 22 2004 14 2001 8
我想按 year 列并添加 count 每个给定年份的列。我希望我的结果是
year
count
year count 2001 46 2004 30 2005 21
我有点费劲想办法,有人能帮忙吗?
希望这能有帮助!! 假设pandas数据帧名为 数据框 . 然后groupby代码运行如下:
df.groupby('year')[['count']].sum()
它将返回您想要的数据帧。
import pandas as pd df = pd.read_csv("test.csv") df['count'] = pd.to_numeric(df['count']) #df['count'] = df.groupby(['year'])['count'].sum() total = df.groupby(['year'])['count'].sum() print(total)
产量:
year 2001 46 2004 30 2005 21