【发布时间】: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 呢?你也想要那个最大值?