【问题标题】:Groupby of different columns with different aggreagation with cumsum for next date具有不同聚合的不同列的 Groupby 与下一个日期的 cumsum
【发布时间】:2021-06-02 06:27:39
【问题描述】:

我有一个按日期和时间排序的数据框:

 ID     Date     Time      A         B      C
 abc   06/Feb     11       12        12     10 
 abc   06/Feb     12       14        13     5
 xyz   07/Feb      1       16        14     50
 xyz   07/Feb      2       18        15     0
 xyz   07/Feb      3       20        16     10

我想按 ID 和日期对其进行分组,并将总和作为分子,计数作为分母,但是对于下一个日期,总和将是以前日期的总和,因此计数作为 cumcount,还有 3 列的最后一个值A,B,C列会增加。如:

ID    Date     A_Num  A_denom   B_Num   B_Denom  C_Num   C_Denom  A_Last  B_Last  C_Last
abc   06/Feb    26       2        25       2      15        2       14      13      5
xyz   07/Feb    54       3        45       3      60        3       20      16      10

我无法一次性完成所有这些..任何人都可以帮助我。提前谢谢。

现在我想将 df1 acc 中的 df2 添加到 id 为:

ID    Date     A_Num  A_denom   B_Num   B_Denom  C_Num   C_Denom  A_Last  B_Last  C_Last
abc   06/Feb    52       4        50       4      30        4       14      13      5
xyz   07/Feb    108      6        90       6      120       6       20      16      10

【问题讨论】:

    标签: python pandas pandas-groupby cumsum


    【解决方案1】:

    您可以在GroupBy.agg 中为每个组聚合sumsizelast,然后选择numdenum 并使用累积和最后添加concat 另一个由聚合@ 创建的DataFrame 987654323@:

    cols = ['A','B','C']
    
    print (df[cols].dtypes)
    A    int64
    B    int64
    C    int64
    dtype: object
    
    d = {'sum':'Num','size':'denom'}
    df1 = df.groupby(['ID','Date'])[cols].agg(['sum','size']).rename(columns=d).cumsum()
    df1.columns = df1.columns.map(lambda x: f'{x[0]}_{x[1]}')
    
    df2 = df.groupby(['ID','Date'])[cols].last().add_suffix('_Last')
    df3 = pd.concat([df1, df2], axis=1).reset_index()
    
    print (df3)
        ID    Date  A_Num  A_denom  B_Num  B_denom  C_Num  C_denom  A_Last  \
    0  abc  06/Feb     26        2     25        2     15        2      14   
    1  xyz  07/Feb     80        5     70        5     75        5      20   
    
       B_Last  C_Last  
    0      13       5  
    1      16      10  
    

    不使用索引写入文件:

    df3.to_csv('file', index=False)
    

    如果解决方案中没有.reset_index

    df3.to_csv('file')
    

    【讨论】:

    • 嗨,我试过了,但我在你的倒数第二行遇到错误,即 df.loc[;,pd.IndexSlice ..... 错误是 TypeError: Unsupported operand type(s)对于 +: 'int' 和 'str'
    • 是的,它们有浮点值。我应该尝试使用 astype(float) 更改他们的类型吗?
    • @naina - 你写入文件的代码是什么?
    • 是的,我在写 index=False 所以它没有来。非常感谢 :)
    • df = df_org.groupby(['ID'])[cols].agg(['sum','size','last']).rename(columns=d) df.loc [:, pd.IndexSlice[:, ['Num', 'denom']]] = df.loc[:, pd.IndexSlice[:, ['Num', 'denom']]] 我正在使用这个..没事吧?
    猜你喜欢
    • 1970-01-01
    • 2018-02-22
    • 2018-10-26
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多