【问题标题】:Pandas groupby a column and set max value in other column as 1 else 0Pandas 按列分组并将其他列中的最大值设置为 1 else 0
【发布时间】:2020-01-24 22:25:06
【问题描述】:

我有一个数据框如下:

df = pd.DataFrame({'unique_id':['x','x' , 'y', 'y'], 'chk':[5, 6, -4, -5], 'score':[5.52363, 6.73939, 7.53637, 3.08375]})

我想按'unique_id' 列分组并在'score' 列中查找最大值并将最大值设置为1,其他设置为0。

我试过df['result'] = df.groupby('unique_id').apply(lambda x: [x.score.idxmax()])

但它给了我空值。我的预期输出是

unique_ID  chk  score  result
x          5   5.52363   0
x          6   6.73939   1
y         -4   7.53637   1
y         -5   3.08375   0

【问题讨论】:

    标签: python pandas group-by max


    【解决方案1】:

    使用GroupBy.transformSeries.eq 来检查值是ma​​xSeries.astype 以获得0 或1

    df['result'] = df['score'].eq(df.groupby('unique_id')
                                    .score
                                    .transform('max')).astype(int)
    print(df)
      unique_id  chk    score  result
    0         x    5  5.52363       0
    1         x    6  6.73939       1
    2         y   -4  7.53637       1
    3         y   -5  3.08375       0
    

    【讨论】:

      猜你喜欢
      • 2018-01-14
      • 2018-11-05
      • 2021-10-02
      • 1970-01-01
      • 2023-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多