python - 在熊猫数据框中查找最大值的索引
问题描述
我有一个带有 m 行和 n 列的 pandas 数据框。我想找到每行中出现的最大值的列索引。
我尝试使用 idxmax,但它只返回第一次出现的最大值。数据框每行有多个最大值,我想获取每一行中最大值的所有索引。
解决方案
这是一个例子numpy
:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(0, 5, (3, 10)))
print(df)
0 1 2 3 4 5 6 7 8 9
0 3 0 0 2 2 4 0 2 1 2
1 3 4 0 4 4 1 1 0 2 3
2 4 1 3 4 4 4 0 3 1 0
res = [np.where(i == np.max(i)) for i in df.values]
print(res)
[array([5], dtype=int64),
array([1, 3, 4], dtype=int64),
array([0, 3, 4, 5], dtype=int64)]
推荐阅读
- firebase - Firebase 使用 gapi 客户端将 defaultLocation:finalize 设置为 Datastore 模式而不是 Native 模式
- r - R中的循环和renderText闪亮
- elixir - 在浏览器 Elixir 中下载分块文件失败
- json - 在 React JS 中解析 JSON 并填充到表中
- javascript - 从另一个 HTML 文件中的表中检索特定行 - Javascript
- c++ - 释放前的临时指针?
- sql - Postgres 生成 json 树
- python - zarr 何时压缩块并将其推送到底层存储系统?
- flutter - 在颤振应用程序中找到资产文件的路径
- vue.js - vue.config.js devServer 未考虑在内