【问题标题】:groupby with multiple condition and operation具有多个条件和操作的 groupby
【发布时间】:2020-08-24 20:15:41
【问题描述】:

我有一个问题,我想对数据框进行分组并执行一些操作。输入数据框是这样的:

我想根据 unique_id 进行分组,但如果有两个观察值,我需要一个唯一 ID 中的两行。 1 个 unique_ID 中可能有任意数量的观察结果

预期输出:

我试图计算它的数量和其他列以帮助 groupby,但我没有为我工作。

df["Count_ob"] = df.groupby("Unique_ID")["IF_car_history"].sum()

已获得帮助。谢谢

【问题讨论】:

    标签: python python-3.x pandas numpy pandas-groupby


    【解决方案1】:
    df = pd.DataFrame({'Unique_id':[1,1,2,2,3,3,3,3],
                       'Car_history':[0,1,0,1,0,1,0,1],
                       'Value':[1000,1500,1000,1200,800,700,1300,1700],
                       'Ob_id':[0,1,0,2,0,3,0,4]})
    
    
    df["Count_ob"] = df.Ob_id[::-1].cumsum()[::-1] # <=== this do the trick!!!
    df["Count_ob"] = df["Count_ob"].max() - df["Count_ob"]
    
    df = df.groupby("Count_ob")[["Unique_id","Car_history","Value","Ob_id"]].agg({'Unique_id':'max',
                                                                            'Car_history':'sum',
                                                                            'Value':'sum',
                                                                            'Ob_id':'sum'}).reset_index(drop=True)
    df['Value'] = df.groupby('Unique_id')['Value'].cumsum().values
    

    【讨论】:

    • 嘿,这确实是个技巧。谢谢你的时间。但是当在唯一 ID 3 和 ob_ID 4 的结果中,我需要添加所有四行 @Marco
    • 你能把你的输出放在马科斯回答之后吗?
    猜你喜欢
    • 2022-01-23
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-26
    • 2016-07-20
    相关资源
    最近更新 更多