对应于pandas DataFrame中最大值的列名 [英] Column name corresponding to largest value in pandas DataFrame
问题描述
针对以下数据框数据:
x y a b c
2 6 12 1 2
1 2 4 6 8
我想要在新列(即d)中返回仅返回a,b,c中具有最大值的列名称的结果.
I want result in new column(i.e d) that returns name of column with max value only among a,b,c.
cols
a
c
我试图从三列中找到最大值并返回列名.但是,我不想选择数据集的所有行,而是只选择这三列中的行.我正在使用以下代码:>
I'm trying to find maximum values from three columns and return column name.But instead of selecting all the rows of dataset,I want to select rows of only these three columns.I'm using the following code:
def returncolname(row, colnames):
return colnames[np.argmax(row.values)]
data['colmax'] = data.apply(lambda x: returncolname(x, data.columns), axis=1)
推荐答案
我能想到的最快的解决方案是DataFrame.dot
:
The fastest solution I can think of is DataFrame.dot
:
df.eq(df.max(1), axis=0).dot(df.columns)
详细信息
首先,计算每行的最大值:
Details
First, compute the maximum per row:
df.max(1)
0 12
1 8
dtype: int64
接下来,找到这些值来自的位置:
Next, find the positions these values come from:
df.eq(df.max(1), axis=0)
x y a b c
0 False False True False False
1 False False False False True
我使用eq
来确保比较在各列之间正确广播.
I use eq
to make sure the comparison is broadcasted correctly across columns.
接下来,使用列列表计算点积:
Next, compute the dot product with the column list:
df.eq(df.max(1), axis=0).dot(df.columns)
0 a
1 c
dtype: object
如果最大值不是唯一的,请使用
If the max is not unique, use
df.eq(df.max(1), axis=0).dot(df.columns + ',').str.rstrip(',')
以逗号分隔的列列表.例如,
To get a comma separated list of columns. For example,
更改几个值:
df.at[0, 'c'] = 12
df.at[1, 'y'] = 8
所有内容都相同,但是请注意,我在每列后面都添加了一个逗号:
Everything is the same, but notice I append a comma to every column:
df.columns + ','
Index(['x,', 'y,', 'a,', 'b,', 'c,'], dtype='object')
df.eq(df.max(1), axis=0).dot(df.columns + ',')
0 a,c,
1 y,c,
dtype: object
从这开始,除去所有结尾的逗号:
From this, strip any trailing commas:
df.eq(df.max(1), axis=0).dot(df.columns + ',').str.rstrip(',')
0 a,c
1 y,c
dtype: object
这篇关于对应于pandas DataFrame中最大值的列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!