Stefano Lombardi
Stefano Lombardi

Reputation: 1591

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:

df.min(axis=1)

which returns 1 10 12.

Instead of the values, I would like to create a pandas Series containing the column labels of the corresponding cells.

That is, I would like to get A A C.

Thanks for any suggestions.

Upvotes: 3

Views: 45

Answers (1)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210832

you can use idxmin(axis=1) method:

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

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

In [11]: df.idxmin(axis=1).values
Out[11]: array(['A', 'A', 'C'], dtype=object)

Upvotes: 3

Related Questions