[英]Find the column name of the max value of a row in a data frame
I am using a pandas data frame in Python and have 121 columns and 5 rows.我在 Python 中使用 Pandas 数据框,有 121 列和 5 行。 I want to find the max value in each row and print the name of the column where it occurs.我想在每一行中找到最大值并打印它出现的列的名称。 I really have no idea how I would even begin to do this but I would appreciate the help.我真的不知道我将如何开始这样做,但我会很感激帮助。
Edit: the column names are strings编辑:列名是字符串
Edit: Some example scenario is:编辑:一些示例场景是:
and for this example I would want something like:对于这个例子,我想要类似的东西:
id: 000621fb3cbb32d8935728e48679680e
breed: african_hunting_dog
confidence: 0.011319
etc for all 3 rows等所有 3 行
You can using idxmax
and max
with axis=1
您可以将idxmax
和max
与axis=1
df.idxmax(axis=1)
df.max(axis=1)
You may try this for beginner:初学者可以试试这个:
import pandas as pd将熊猫导入为 pd
df = pd.DataFrame({'Col1':['A','B','C','D','E'], 'Col2': [4,2,6,3,2], 'Col3':[3,6,4,3,1]})
for x in range(len(df)):
dt = df.iloc[x]
if dt[1] > dt[2]:
print ('Col2:{}'.format(dt[1]))
elif dt[1] < dt[2]:
print ('Col3:{}'.format(dt[2]))
else:
print ('Both cols are same')
for col in df.columns:
if df[col].values[-1] == df.iloc[-1].max():
print(col)
or alternatively或者
[x if df[x].values[-1] == df.iloc[-1].max() for x in df.columns]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.