在分层数据框架上使用idxmax

2024-09-30 05:28:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在多索引数据帧中找到多列中最大值的索引。你知道吗

        Kommune  Upplands  Vallentuna...   Kiruna
Year    Party  
1973    M        0.9       29.2      ...   20     
        KD       15        10        ...   2 
        MP       1.1       4         ...   5     
        V        6         7         ...   8  
        SD       NaN       NaN       ...   NaN
        L        10.1      13.5      ...   8.8 
1976    M        1.8       29.2      ...   20     
        KD       16        10        ...   2 
        MP       10        4         ...   5     
        V        15        7         ...   8    
        SD       NaN       NaN       ...   NaN
        L        11.9      15        ...   18
...     ...      ...       ...       ...   ... 
...     ...      ...       ...       ...   ... 
2014    M        28        22        ...   29     
        KD       4.5       13        ...   5 
        MP       11        8         ...   9     
        V        1.9       5         ...   10    
        SD       20        10        ...   5
        L        19        25        ...   1

所需输出为

Kommune  Upplands  Vallentuna...   Kiruna
Year      
1973     KD        M         ...   M
1976     V         M         ...   M
...      ...       ...       ...   ...
2014     M         L         ...   M  

我试过使用groupby(正如前面一篇关于多索引Getting max values from pandas multiindex dataframe的文章所建议的那样),但是它会为每个位置返回一个元组。你知道吗

Kommune  Upplands          Vallentuna        ...   Kiruna
Year      
1973     (1973, KD)        (1973, M)         ...   (1973, M)
1976     (1976, V)         (1976, M)         ...   (1976, M)
...      ...               ...               ...   ...
2014     (2014, M)         (2014, L)         ...   (2014, M)

如何从每个元组中仅获取第二个元素?或者有没有更有效的方法来找到指数?你知道吗


Tags: 数据partympsdnanyearmaxkd
2条回答

看来你需要

df.stack().sort_values().groupby(level=[0,2]).tail(1).reset_index(level=1).Party.unstack()
Out[544]: 
     Upplands Vallentuna Kiruna
Year                           
1973       KD          M      M
1976       KD          M      M

How do I get only the second element from each tuple?

一种解决方案是通过^{}提取每个tuple的第二个元素:

df = pd.DataFrame([[(1, 2), (3, 4)], [(5, 6), (7, 8)]])

res = df.applymap(lambda x: x[1])

print(res)

   0  1
0  2  4
1  6  8

或使用功能替代方案:

from operator import itemgetter

res = df.applymap(itemgetter(1))

相关问题 更多 >

    热门问题