查找具有最高值的列(熊猫)

fut*_*ime 3 python dataframe 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]
Run Code Online (Sandbox Code Playgroud)

等等。

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

jez*_*ael 5

您可以使用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
Run Code Online (Sandbox Code Playgroud)

随机重复性最大值更复杂。

您可以首先通过 找到所有max值x[(x == x.max())]。然后你需要index值,在那里 apply sample。但它仅适用Series,因此index被转换为 Series通过to_series。最后,您只能选择Serieby 的第一个值iloc:

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
Run Code Online (Sandbox Code Playgroud)
#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
Run Code Online (Sandbox Code Playgroud)