如何根据第一级最大值过滤MultiIndex数据帧?

时间:2018-12-18 19:25:55

标签: python python-3.x pandas dataframe

我有以下数据框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

通过获取每个max中的second first

我尝试做s.groupby(level=1).apply(max),但这返回:

second
1   -0.337298
2    0.780388
dtype: float64

很明显,我的尝试返回了second中每个组的最大值,而不是每个max的{​​{1}} second

有什么想法吗?

2 个答案:

答案 0 :(得分:4)

使用idxmax和布尔索引:

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

答案 1 :(得分:3)

使用sort_values + tail

s.sort_values().groupby(level=0).tail(1)
Out[33]: 
first  second
bar    2        -1.806466
baz    2        -0.776890
foo    1        -0.641193
qux    2        -0.455319
dtype: float64