如何获得最大值的索引和列?

时间:2019-05-13 16:56:23

标签: python pandas

我想获取总数最大的索引和值(非零)。

A = np.matrix([[0,2,1,0],
               [0,0,0,0],
               [1,3,0,1],])
slst = ['S1','S2','S3','S4']
namelist= ['Alice','John','Joe']
df =  pd.DataFrame(A,columns = slst, index = namelist)
df.loc['total'] = df.select_dtypes(pd.np.number).sum()
print (df)
Output:
       S1  S2  S3  S4
Alice   0   2   1   0
John    0   0   0   0
Joe     1   3   0   1
total   1   5   1   1

我想从下表中获得结果。 如何获得?

Output1:
Alice: 2,
Joe: 3

2 个答案:

答案 0 :(得分:2)

这也应该起作用:

df1 = df.max(axis=1)
df1

       S1  S2  S3  S4
Alice   0   2   1   0
John    0   0   0   0
Joe     1   3   0   1
total   1   5   1   1

Alice    2
John     0
Joe      3
total    5
dtype: int64

答案 1 :(得分:1)

不要做df.loc['total'],请尝试:

total = df.select_dtypes(pd.np.number).sum()
df[total.idxmax()]

输出:

Alice    2
John     0
Joe      3
total    5
Name: S2, dtype: int64
相关问题