【问题标题】:Pandas: replace certain values within groups using group maximus熊猫:使用组最大值替换组内的某些值
【发布时间】:2023-02-01 01:25:42
【问题描述】:

这是我的桌子:

category number probability
1102 24 0.3
1102 18 0.6
1102 16 0.1
2884 24 0.16
2884 15 0.8
2884 10 0.04

所以我想用组内概率最高的数字替换概率低于 15% 的数字列:

category number probability
1102 24 0.3
1102 18 0.6
1102 18 0.1
2884 24 0.16
2884 15 0.8
2884 15 0.04

【问题讨论】:

  • 类别中的 1002 应该是 1102 吗?
  • 是的,很抱歉,现在会更正它

标签: python pandas dataframe


【解决方案1】:

在一组中找到与最大概率对应的数字,然后使用 loc 更新值

n = df.sort_values('probability').groupby('category')['number'].transform('last')
df.loc[df['probability'] <= 0.15, 'number'] = n

   category  number  probability
0      1102      24         0.30
1      1102      18         0.60
2      1102      18         0.10
3      2884      24         0.16
4      2884      15         0.80
5      2884      15         0.04

【讨论】:

    【解决方案2】:

    使用drop_duplicates 获取概率最高的数字,然后替换为np.where

    highest_prob = df.sort_values('probability').drop_duplicates('category', keep='last').set_index('category')['number')
    
    df['number'] = np.where(df['probability'] < 0.15, df['category'].map(highest_prob), df['number'])
    

    【讨论】:

    • 这可行,但 sort_values 需要使用“概率”而不是“数字”
    • @Zichaun 更新了。谢谢。
    【解决方案3】:

    使用 idxmaxnumpy.where 的可能解决方案:

    ser = df.groupby("category")["number"].transform("idxmax")
    ​
    df["number"] = np.where(df["probability"].lt(0.15), ser , df["number"])
    ​
    

    输出 :

    print(df)
       category  number  probability
    0      1102      24         0.30
    1      1102      18         0.60
    2      1002       2         0.10
    3      2884      24         0.16
    4      2884      15         0.80
    5      2884       3         0.04
    

    【讨论】:

    • 为什么投反对票?
    猜你喜欢
    • 1970-01-01
    • 2017-03-04
    • 2018-11-19
    • 2014-10-09
    • 2023-03-06
    • 2019-10-21
    • 1970-01-01
    • 2018-06-17
    • 2020-04-28
    相关资源
    最近更新 更多