我有以下数据框:
a b c d e
1 .90 .95 .83 .56
.95 .96 .87 .83 .63
.83 .87 .83 .95 .81
我如何找到每行的最大值及其所属的列,使其看起来像这样:
a 1
b .96
d .95
答案 0 :(得分:4)
尝试一下:
result = df.max(axis=1)
result.index = df.idxmax(axis=1)
答案 1 :(得分:4)
s=pd.Series(df.columns[np.argmax(df.values,axis=1)])
final=pd.DataFrame(df.lookup(s.index,s),s)
答案 2 :(得分:2)
您可以使用idxmax()
函数:
import pandas as pd
a = {'a':[100,95,83],'b':[90,96,87],'c':[95,87,83],'d':[83,83,95],'e':[56,63,81]}
df = pd.DataFrame(a)
print(df)
数据框如下所示:
a b c d e
0 100 90 95 83 56
1 95 96 87 83 63
2 83 87 83 95 81
使用函数idxmax,我们可以得出每行最大值属于哪一列:
print(df.idxmax(axis=1))
输出:
0 a
1 b
2 d
将其与原始数据帧连接起来,以得到对应的值(给定其所属的列)。
df_result = pd.concat([df.idxmax(axis=1),df.max(axis=1)],axis=1)
print(df_result)
输出:
0 1
0 a 100
1 b 96
2 d 95
答案 3 :(得分:1)
maxRow = df.idxmax(1)
maxValue = df.max(1)
print(pd.concat([maxRow , maxValue],1))
maxRow
变量给出数据框中最大值行的id,将轴设置为行而不是列的1,同样,maxValue
获得行的maxValues
pd.concat
将这两个列表压缩到一个数据框中