Python 返回表示每组中最大值的索引的一系列数字位置

Python 返回表示每组中最大值的索引的一系列数字位置,python,pandas,Python,Pandas,以系列为例: np.random.seed([3,1415]) s = pd.Series(np.random.rand(100), pd.MultiIndex.from_product([list('ABDCE'), list('abcde'), ['One', 'Two', 'Three', 'Fo

以系列为例:

np.random.seed([3,1415])
s = pd.Series(np.random.rand(100),
              pd.MultiIndex.from_product([list('ABDCE'),
                                          list('abcde'),
                                          ['One', 'Two', 'Three', 'Four']]))
我可以
groupby
索引级别的组合,并获得
idxmax

s.groupby(level=[0, 2]).idxmax()

A  Four      (A, c, Four)
   One        (A, d, One)
   Three    (A, c, Three)
   Two        (A, d, Two)
B  Four      (B, d, Four)
   One        (B, d, One)
   Three    (B, c, Three)
   Two        (B, b, Two)
C  Four      (C, b, Four)
   One        (C, a, One)
   Three    (C, a, Three)
   Two        (C, e, Two)
D  Four      (D, b, Four)
   One        (D, e, One)
   Three    (D, b, Three)
   Two        (D, c, Two)
E  Four      (E, c, Four)
   One        (E, a, One)
   Three    (E, c, Three)
   Two        (E, a, Two)
dtype: object
我想要每组中每个的数字位置

我可以通过

但是我想要这个:

A  Four     2
   One      3
   Three    2
   Two      3
B  Four     3
   One      3
   Three    2
   Two      1
C  Four     1
   One      0
   Three    0
   Two      4
D  Four     1
   One      4
   Three    1
   Two      2
E  Four     2
   One      0
   Three    2
   Two      0
dtype: int64
我就是这样做的:

s.groupby(level=[0, 2]).apply(lambda x: x.index.get_loc(x.idxmax()))

A  Four     2
   One      3
   Three    2
   Two      3
B  Four     3
   One      3
   Three    2
   Two      1
C  Four     1
   One      0
   Three    0
   Two      4
D  Four     1
   One      4
   Three    1
   Two      2
E  Four     2
   One      0
   Three    2
   Two      0
dtype: int64

我终于有了一个解决方案,它使用NumPy的整形方法,然后沿着其中一个轴操作,得到
argmax
。我不确定这是否优雅,但我希望在性能方面会很好。此外,我假设多索引数据的pandas系列具有常规格式,即每个级别保持所有索引中的元素数量

下面是实现-

L0,L1,L2 = s.index.levels[:3]
IDs = s.sortlevel().values.reshape(-1,len(L0),len(L1),len(L2)).argmax(2)
sOut = pd.Series(IDs.ravel(),pd.MultiIndex.from_product([L0,L2]))

时间安排(pir的补充)


@piRSquared Phew,我在过去一个小时左右探索多索引熊猫的东西时学到的东西真是太疯狂了!所以在最好的时候!:D
L0,L1,L2 = s.index.levels[:3]
IDs = s.sortlevel().values.reshape(-1,len(L0),len(L1),len(L2)).argmax(2)
sOut = pd.Series(IDs.ravel(),pd.MultiIndex.from_product([L0,L2]))