Andrés Braga
Andrés Braga

Reputation: 59

Get column index label based on values

I have the following:

          C1       C2     C3
0         0        0      1 
1         0        0      1
2         0        0      1

And i would like to get the corresponding column index value that has 1's, so the result should be "C3".

I know how to do this by transposing the dataframe and then getting the index values, but this is not ideal for data in the dataframes i have, and i wonder there might be a more efficient solution?

Upvotes: 1

Views: 130

Answers (1)

ansev
ansev

Reputation: 30920

I will save the result in a list because otherwise there could be more than one column with values ​​equal to 1. You can use DataFrame.loc

if all column values ​​must be 1 then you can use:

df.loc[:,df.eq(1).all()].columns.tolist()

Output:

['C3']

if this isn't necessary then use:

df.loc[:,df.eq(1).any()].columns.tolist()

or as suggested @piRSquared, you can select directly from df.columns:

[*df.columns[df.eq(1).all()]]

Upvotes: 1

Related Questions