繁体   English   中英

查找具有最高值(pandas)的列

[英]Find column with the highest value (pandas)

我有一个Pandas数据框,其中有几列,范围从0到100.我想在数据框中添加一列,其中包含列中的每个行具有最大值的列的名称。 所以:

one   two   three four  COLUMN_I_WANT_TO_CREATE
5     40    12    19    two
90    15    58    23    one
74    95    34    12    two
44    81    22    97    four
10    59    59    44    [either two or three, selected randomly]

等等

如果解决方案可以随机解决关系,则奖励积分。

您可以将idxmax与参数axis=1

print df
   one  two  three  four
0    5   40     12    19
1   90   15     58    23
2   74   95     34    12
3   44   81     22    97

df['COLUMN_I_WANT_TO_CREATE'] = df.idxmax(axis=1)
print df
   one  two  three  four COLUMN_I_WANT_TO_CREATE
0    5   40     12    19                     two
1   90   15     58    23                     one
2   74   95     34    12                     two
3   44   81     22    97                    four

随机双重最大值是更复杂。

您可以先通过x[(x == x.max())]查找所有max 然后你需要index值,其中apply sample 但它仅适用于Series ,因此index将转换为Series by to_series 最后你可以只选择iloc第一个Serie值:

print df
   one  two  three  four
0    5   40     12    19
1   90   15     58    23
2   74   95     34    12
3   44   81     22    97
4   10   59     59    44
5   59   59     59    59
6   10   59     59    59
7   59   59     59    59
#first run
df['COL']=df.apply(lambda x:x[(x==x.max())].index.to_series().sample(frac=1).iloc[0], axis=1)
print df
   one  two  three  four    COL
0    5   40     12    19    two
1   90   15     58    23    one
2   74   95     34    12    two
3   44   81     22    97   four
4   10   59     59    44  three
5   59   59     59    59    one
6   10   59     59    59    two
7   59   59     59    59  three

#one of next run
df['COL']=df.apply(lambda x:x[(x==x.max())].index.to_series().sample(frac=1).iloc[0], axis=1)
print df
   one  two  three  four    COL
0    5   40     12    19    two
1   90   15     58    23    one
2   74   95     34    12    two
3   44   81     22    97   four
4   10   59     59    44    two
5   59   59     59    59    one
6   10   59     59    59  three
7   59   59     59    59   four

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM