我有以下数据框 s
:
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
[1, 2, 1, 2, 1, 2, 3, 2,]]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
s = pd.Series(np.random.randn(8), index=index)
first second
bar 1 -0.493897
2 -0.274826
baz 1 -0.337298
2 -0.564097
foo 1 -1.545826
2 0.159494
qux 3 -0.876819
2 0.780388
dtype: float64
我想将其转换为:
first second
bar 2 -0.274826
baz 2 -0.564097
foo 2 0.159494
qux 3 -0.876819
dtype: float64
通过取每个 first
的 max
second
。
我尝试执行 s.groupby(level=1).apply(max)
,但这会返回:
second
1 -0.337298
2 0.780388
dtype: float64
很明显,我的尝试在 second
中返回每个组的最大值,而不是每个 first
的 max
second
>.
知道怎么做吗?
最佳答案
使用idxmax
和 bool 索引:
s[s.groupby(level=0).idxmax()]
输出:
first second
bar 2 0.482328
baz 1 0.244788
foo 2 1.310233
qux 2 0.297813
dtype: float64
关于python - 如何根据一级最大值过滤 MultiIndex 数据帧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53839780/