Encuentre el nombre de la columna que tiene el valor máximo para cada fila
Tengo un DataFrame como este:
In [7]:
frame.head()
Out[7]:
Communications and Search Business General Lifestyle
0 0.745763 0.050847 0.118644 0.084746
0 0.333333 0.000000 0.583333 0.083333
0 0.617021 0.042553 0.297872 0.042553
0 0.435897 0.000000 0.410256 0.153846
0 0.358974 0.076923 0.410256 0.153846
Aquí, quiero preguntar cómo obtener el nombre de la columna que tiene el valor máximo para cada fila, la salida deseada es así:
In [7]:
frame.head()
Out[7]:
Communications and Search Business General Lifestyle Max
0 0.745763 0.050847 0.118644 0.084746 Communications
0 0.333333 0.000000 0.583333 0.083333 Business
0 0.617021 0.042553 0.297872 0.042553 Communications
0 0.435897 0.000000 0.410256 0.153846 Communications
0 0.358974 0.076923 0.410256 0.153846 Business
3 answers
Puede utilizar idxmax
con axis=1
para encontrar la columna con el mayor valor en cada fila:
>>> df.idxmax(axis=1)
0 Communications
1 Business
2 Communications
3 Communications
4 Business
dtype: object
Para crear la nueva columna 'Max', utilice df['Max'] = df.idxmax(axis=1)
.
Para encontrar el índice row en el que se encuentra el valor máximo en cada columna, use df.idxmax()
(o equivalentemente df.idxmax(axis=0)
).
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-01 13:20:41
Y si desea producir una columna que contenga el nombre de la columna con el valor máximo, pero considerando solo un subconjunto de columnas, entonces use una variación de la respuesta de @ajcr:
df['Max'] = df[['Communications','Business']].idxmax(axis=1)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-02 09:24:05
Podrías apply
en dataframe y obtener argmax()
de cada fila a través de axis=1
In [144]: df.apply(lambda x: x.argmax(), axis=1)
Out[144]:
0 Communications
1 Business
2 Communications
3 Communications
4 Business
dtype: object
Aquí hay un punto de referencia para comparar cuán lento es el método apply
para idxmax()
para len(df) ~ 20K
In [146]: %timeit df.apply(lambda x: x.argmax(), axis=1)
1 loops, best of 3: 479 ms per loop
In [147]: %timeit df.idxmax(axis=1)
10 loops, best of 3: 47.3 ms per loop
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-28 12:30:12