【问题标题】:keeping entire rows after applying groupby with a certain method [duplicate]用某种方法应用groupby后保留整行[重复]
【发布时间】:2019-05-31 03:49:39
【问题描述】:

我有一个如下的数据框: data_frame:

column_A column_B, column_C
  2        3        5            row= 0
  2        3        6            row= 1
  3        4        2            row= 2
  3        4        9            row= 3

我要做的是检查它们的 column_A 和它们的 column_B 具有相同值的行,并获得每个组的最大值: 更准确地说:在我的例子中,我想获得第 1 行和第 3 行。 所以预期的输出应该是:

column_A column_B, column_C
  2        3        6            row= 1
  3        4        9            row= 3

我尝试将 groupbyma​​x 方法 应用于 column_C:它似乎有效,但我得到的输出是 column_C。这是我的代码:

test_df=pd.DataFrame([[2,3,5],[2,3,6],[3,4,2],[3,4,9]],columns=['column_A','column_B','column_C'])
result= test_df.groupby(['column_A','column_B'], sort=False)['column_C'].max()
print(result)

这是结果

column_A  column_B
2         3           6
3         4           9
Name: column_C, dtype: int64

我知道为什么我有一个系列(因为我在 column_C 上应用了 max 方法),但我想不出一种方法来获取相应的行,而不是只获取 column_C 值。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用sort_values +drop_duplicates

    df.sort_values('column_C').drop_duplicates(['column_A','column_B'],keep='last')
    Out[186]: 
       column_A  column_B  column_C
    1         2         3         6
    3         3         4         9
    

    【讨论】:

      猜你喜欢
      • 2018-09-23
      • 2021-10-26
      • 2021-11-01
      • 1970-01-01
      • 2014-01-15
      • 2019-06-10
      • 1970-01-01
      • 2018-06-25
      • 2018-06-11
      相关资源
      最近更新 更多