python - 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
任何帮助表示赞赏,谢谢!
解决方案
错误意味着有一些非数字列。
仅选择数字列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
推荐阅读
- flutter - 我无法解决这个错误,请帮助我!错误:“StorageUploadTask”不是类型
- java - 如何将项目动态添加到 ListView 的自定义适配器
- vue.js - 如何停止 BootstrapVue 轮播循环?
- mongodb - OpsManager 应用程序无法连接到启用 SSL/TLS 的 opsmanager 数据库
- linq - “IEnumerable<>”不包含“OrderBy”的定义
- c - 关于`sprintf`和`nm`
- mysql - 更改生产服务器中的mysql表结构
- wso2 - 在 WSO2 3.0.0 APIM 中设置多个流量管理器
- sql-server - 如何在 SQL Server 中设置更新事件的时间戳?
- tensorflow - `tensorflowjs_converter` 导致浏览器中的模型无法检测到任何对象