【问题标题】:Selecting row by maximum value from hierachical DataFrame从分层DataFrame中按最大值选择行
【发布时间】:2019-12-05 22:22:48
【问题描述】:

这是我的数据框:

import numpy as np
import pandas as pd

data = {('California', 2000): [33871648, 45],
        ('California', 2010): [37253956, 52],
        ('Texas', 2000): [20851820, 56],
        ('Texas', 2010): [25145561, 34],
        ('New York', 2000): [18976457, 23],
        ('New York', 2010): [19378102, 23]}
df = pd.DataFrame(data).T
df.index.names = 'State', 'Year'
df.columns = ['population', 'foo']
print(df)

                 population  foo
State      Year                 
California 2000    33871648   45
           2010    37253956   52
Texas      2000    20851820   56
           2010    25145561   34
New York   2000    18976457   23
           2010    19378102   23

我想要每个 State 的最大 foo 行,但如果我尝试

idx = df.groupby(level=0)['foo'].apply(np.argmax)
print(df.loc[idx])

当我尝试按级别 0 分组并应用 np.argmax 时,我收到警告:

... FutureWarning: 
The current behaviour of 'Series.argmax' is deprecated, use 'idxmax'
instead.
The behavior of 'argmax' will be corrected to return the positional
maximum in the future. For now, use 'series.values.argmax' or
'np.argmax(np.array(values))' to get the position of the maximum
row.
  return getattr(obj, method)(*args, **kwds)
                 population  foo
State      Year                 
California 2010    37253956   52
New York   2000    18976457   23
Texas      2000    20851820   56

它有效,但我应该如何正确地做到这一点?我不确定我是否理解警告消息中的建议。 这个问题有点像this one,但我想要整行,而不仅仅是最大值。

【问题讨论】:

  • foo 相同时,level1 呢?你也想要那个最大值?

标签: python pandas dataframe


【解决方案1】:

使用transform('max')再与foo比较,保留符合条件的记录:

df[df.foo.eq(df.groupby(level=0)['foo'].transform('max'))]

                 population  foo
State      Year                 
California 2010    37253956   52
Texas      2000    20851820   56
New York   2000    18976457   23
           2010    19378102   23

【讨论】:

  • 由于原始问题没有显示New York 的两行,因此可能不需要重复。如果您只想要第一个结果,您可能应该附加:.drop_duplicates(["State", "foo"], keep="first")
  • 好的……这行得通。我刚刚注意到df.loc[df.groupby(level=0)['foo'].idxmax()] 也是如此。有什么理由比另一种更喜欢一种解决方案吗?
  • @xnx 给出的输出略有不同,因为此解决方案将level=0 分组,因此它不会丢弃level=,其中foo 相同。您说“我想要每个州的最大 foo 行”,这是正确的 sol(IMO)。您可以测试时间虽然
猜你喜欢
  • 1970-01-01
  • 2023-01-04
  • 2017-12-07
  • 1970-01-01
  • 2022-06-23
  • 1970-01-01
  • 1970-01-01
  • 2018-06-08
  • 2013-07-22
相关资源
最近更新 更多