Stezzo Stezzo - 1 year ago 71
Python Question

Extracting column labels of the cells meeting a given condition

Suppose the data at hand is in the following form:

import pandas as pd
df = pd.DataFrame({'A':[1,10,20], 'B':[4,40,50], 'C':[10,11,12]})

I can compute the minimum by row with:


which returns
1 10 12
Instead of the values, I would like to create a pandas Series containing the colum labels of the correponding cells.
That is, I would like to get

Thanks for any suggestions.

Answer Source

you can use idxmin(axis=1) method:

In [8]: df.min(axis=1)
0     1
1    10
2    12
dtype: int64

In [9]: df.idxmin(axis=1)
0    A
1    A
2    C
dtype: object

In [11]: df.idxmin(axis=1).values
Out[11]: array(['A', 'A', 'C'], dtype=object)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download