【问题标题】:groupby column while showing other columnsgroupby 列同时显示其他列
【发布时间】:2017-06-17 14:00:55
【问题描述】:

我有一个数据集如下:

name | $ | letter
adam, 34,  c
beny, 45,  e
adam, 55,  a
beny, 87,  t

我想提取每个名字捐赠的最高 $ 以及相应的字母。 所以对于 Adam,我会得到:adam,55,a。

如果我使用:

df.groupby('name')[['$']].max()

这并没有给我相应的信。

如果我使用:

df.groupby('name')[['$','letter']].max()

我得到了字母表中最大的 $ 和最高的字母。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用DataFrameGroupBy.idxmax作为最大值索引,然后通过loc选择:

    print (df.groupby('name')['$'].idxmax())
    name
    adam    2
    beny    3
    Name: $, dtype: int64
    
    df = df.loc[df.groupby('name')['$'].idxmax()]
    print (df)
       name   $ letter
    2  adam  55      a
    3  beny  87      t
    

    另一种解决方案先使用sort_values,然后使用GroupBy.last

    df = df.sort_values('$').groupby('name', as_index=False).last()
    print (df)
       name   $ letter
    0  adam  55      a
    1  beny  87      t
    

    解决方案的不同之处在于idxmax 让原始索引,last 重置它们。

    【讨论】:

    • 谢谢。我很感激。
    猜你喜欢
    • 2014-06-17
    • 2021-07-03
    • 1970-01-01
    • 2016-03-28
    • 2020-03-17
    • 2021-06-14
    相关资源
    最近更新 更多