首页 > 解决方案 > 在熊猫数据框中查找最大值的索引

问题描述

我有一个带有 m 行和 n 列的 pandas 数据框。我想找到每行中出现的最大值的列索引。

我尝试使用 idxmax,但它只返回第一次出现的最大值。数据框每行有多个最大值,我想获取每一行中最大值的所有索引。

标签: pythonpandas

解决方案


这是一个例子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)]

推荐阅读