这是我的数据框:

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


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

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,但是我想要整行,而不仅仅是最大值。

最佳答案

使用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

关于python - 从分层数据框中按最大值选择行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57239247/

10-14 14:52
查看更多