gpt4 book ai didi

python - 如何在 pandas 数据框上应用 groupby 两次?

转载 作者:行者123 更新时间:2023-12-02 06:31:10 25 4
gpt4 key购买 nike

我有 pandas 数据框,其中包含“年”、“月”和“交易 ID”列。我想获取每年每个月的交易数量。例如,我的数据如下:

year: {2015,2015,2015,2016,2016,2017}
month: {1, 1, 2, 2, 2, 1}
tid: {123, 343, 453, 675, 786, 332}

我希望获得输出,以便每年我都能获得每月的交易数量。对于 2015 年的 ex,我将得到输出:

month: [1,2]
count: [2,1]

我使用了groupby('year')。但之后我如何才能获得每月的交易数量。

最佳答案

您需要groupby按两列 - ,然后汇总 size :

year = [2015,2015,2015,2016,2016,2017]
month = [1, 1, 2, 2, 2, 1]
tid = [123, 343, 453, 675, 786, 332]

df = pd.DataFrame({'year':year, 'month':month,'tid':tid})
print (df)
month tid year
0 1 123 2015
1 1 343 2015
2 2 453 2015
3 2 675 2016
4 2 786 2016
5 1 332 2017

df1 = df.groupby(['year','month'])['tid'].size().reset_index(name='count')
print (df1)
year month count
0 2015 1 2
1 2015 2 1
2 2016 2 2
3 2017 1 1

关于python - 如何在 pandas 数据框上应用 groupby 两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45561118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com