【问题标题】:How I can apply groupby two times on pandas data frame?如何在熊猫数据框上应用 groupby 两次?
【发布时间】:2018-01-15 14:21:50
【问题描述】:

我有带有“年”、“月”和“交易 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')。但在那之后我怎么能得到每月的交易计数。

【问题讨论】:

    标签: python pandas group-by


    【解决方案1】:

    两列都需要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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-09
      • 2013-12-19
      • 2021-04-30
      • 2018-08-01
      • 2021-12-06
      • 2017-05-18
      • 1970-01-01
      • 2022-11-13
      相关资源
      最近更新 更多