【问题标题】:How to display column value based on frequency value of another column in pandas?如何根据熊猫中另一列的频率值显示列值?
【发布时间】:2018-03-10 00:28:35
【问题描述】:

我有一个数据框,其中“代码”行填充了代码,“注释”行填充了注释。由于代码意味着我想计算它们的频率。例如。使用 .value_counts(),然后我还想知道任何唯一代码都附有什么注释。

例如,代码 A 在其中一行有注释“adam”。现在我想计算有多少个 A,并将其中一个注释显示给任何一个 A。 (我不想单独计算每个代码,而是一次显示所有代码的频率)

例子:

IN:
code  note
A     adam
A     august
A     abdul
B     bree
B     bar
A     august
B     barnie
B     barnie
C     ceasar
C     coolio
A     august


OUT:
A     5     adam
B     4     bree
C     2     ceasar

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    agg 与两个 aggfunc 一起使用 - countfirst

    df.groupby('code').note.agg(['count', 'first'])
    
          count   first
    code               
    A         5    adam
    B         4    bree
    C         2  ceasar
    

    【讨论】:

    • 以及如何按降序排列?
    • @AnonX 使用 sort_values: df.groupby('code').note.agg(['count', 'first']).sort_values('count', ascending=False)
    猜你喜欢
    • 2019-09-29
    • 2020-11-26
    • 2020-12-11
    • 2018-04-06
    • 1970-01-01
    • 1970-01-01
    • 2020-10-27
    • 1970-01-01
    • 2022-11-16
    相关资源
    最近更新 更多