首页 > 解决方案 > Pandas Dataframe:使用 idxmax() 查找每列的最大值索引

问题描述

我有一个 156 x 9 的数据框,没有空值,我试图找到每列最大值的索引。我尝试了以下

    country_list = []
    keys = []
    for i in range(len(col)):
        country = df.loc[df[col[i]].idxmax()]['Country or region']
        country_list.append(country)
        keys.append(col[i])

可用的列是

In[65]:df.columns
Out[65]: 
Index(['Overall rank', 'Country or region', 'Score', 'GDP per capita',
       'Social support', 'Healthy life expectancy',
       'Freedom to make life choices', 'Generosity',
       'Perceptions of corruption'],
      dtype='object')

但我得到了使用 idxmax 的错误TypeError: reduction operation 'argmax' not allowed for this dtype

任何帮助表示赞赏,谢谢!

标签: pythonpandasdataframe

解决方案


错误意味着有一些非数字列。

仅选择数字列DataFrame.select_dtypes,然后使用DataFrame.idxmax

df = pd.DataFrame({
        'A':list('abcdef'),
         'B':[4,5,4,5,5,4],
         'C':[7,8,9,4,2,3],
         'D':[1,3,5,7,1,0],
         'E':[5,3,6,9,2,4],
         'F':list('aaabbb')
})

print (df)
   A  B  C  D  E  F
0  a  4  7  1  5  a
1  b  5  8  3  3  a
2  c  4  9  5  6  a
3  d  5  4  7  9  b
4  e  5  2  1  2  b
5  f  4  3  0  4  b

df1 = df.select_dtypes(np.number).idxmax()
print (df1)
B    1
C    2
D    3
E    3
dtype: int64

推荐阅读