如何在 Pandas 数据框上应用 groupby 两次?

neh*_*eha 5 python group-by pandas

我有带有“年”、“月”和“交易ID”列的熊猫数据框。我想获得每年每个月的交易次数。例如,我的数据如下:

year: {2015,2015,2015,2016,2016,2017}
month: {1,  1,   2,   2,   2,    1}
tid: {123,  343, 453, 675, 786, 332}
Run Code Online (Sandbox Code Playgroud)

我想得到这样的输出,每年我都会得到每月的交易数量。对于 2015 年的前任,我将得到输出:

month: [1,2]
count: [2,1]
Run Code Online (Sandbox Code Playgroud)

我使用了 groupby('year')。但在那之后我如何获得每月的交易计数。

jez*_*ael 7

你需要groupby通过两列-yearmonth,然后汇总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
Run Code Online (Sandbox Code Playgroud)