【问题标题】:update column values based on groupby output根据 groupby 输出更新列值
【发布时间】:2021-02-27 19:49:56
【问题描述】:

我有多索引 df,其中一个日期索引可以有多个记录。如何为每个bond_name 的最大col_1 更新col_2?我有什么:

date        bond_name    col_1   col_2
2020-11-15  aaa          0.5     t1
            bbb          0.5     t1
2020-11-16  ccc          0.75    t1
2020-11-20  bbb          0.9     t1
            ddd          0.9     t1
2020-11-29  ddd          0.95    t1

以及想要的输出:

date        bond_name    col_1   col_2
2020-11-15  aaa          0.5     t2
            bbb          0.5     t1
2020-11-16  ccc          0.75    t2
2020-11-20  bbb          0.9     t2
            ddd          0.9     t1
2020-11-29  ddd          0.95    t2

【问题讨论】:

    标签: python pandas dataframe filter group-by


    【解决方案1】:

    检查idxmax

    df.loc[df.groupby('date')['col_1'].idxmax(),'col_2'] = 't2'
    df
    Out[83]: 
                          col_1 col_2
    date       bond_name             
    2020-11-15 aaa         0.50    t2
               bbb         0.50    t1
    2020-11-16 ccc         0.75    t2
    2020-11-20 bbb         0.90    t2
               ddd         0.90    t1
    2020-11-29 ddd         0.95    t2
    

    【讨论】:

    • df.groupby(level='bond_name')['col_1'].idxmax() 给出ValueError
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 2018-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    • 1970-01-01
    相关资源
    最近更新 更多