简体   繁体   English

查找数据框中某行最大值的列名

[英]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您可以将idxmaxmaxaxis=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.

相关问题 创建一个数据框作为行索引值和列名的函数? - create a Data frame as a function of row index value and column name? 熊猫:查找列名和值,每一行的最大值(和第二最大值) - Pandas: find column name and value with max (and second max) value for each row 数据框,子集用户名并打印最大值并打印子集中每一列的最大值 - Data Frame, Subset the user name and print the max and print the max value of each column in the subset 从数据框中的每列查找Max - Find Max from each column in data frame 如果一列有'x'值,则从行中的其他列中找到最大值,并将x更改为最大列名的值 - If a column has 'x' value, find max value from other columns in row, and change x to the value of max column name 无法找到最大索引行的列值 - Unable to find column value of max index row 查找并返回最大值的行和最大值的行作为数组 - Find and return max value for a column and the row of the max value as an array 在一行中查找最后一次出现的最大值并在 Pandas Python 中获取列名 - Find last occurrence of a max value in a row and get Column name in Pandas Python 根据列值突出显示数据框中的行? - Highlight row in a data frame based on a column value? 取数据框中每一行的 predict_proba 的最大值 - Taking the max value of predict_proba for each row in a data frame
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM