Home > OS >  Get Column Index based on Value rather than Column Label
Get Column Index based on Value rather than Column Label

Time:10-31

Say I have the following Dataframe.

df = pd.DataFrame([["a", "b", "c"], ["d", "e", "f"],["g", "h", "i"]])

How do I get the column index of "c" in row 0?

I know there are ways to get the column index if there are column labels, but I can't find ways to return the column index just based on the cell value, if searching a particular row.


CodePudding user response:

Here's one way:

You can create a extra dataframe that check each cell value in your original dataframe to locate the string inside each cell. Here you would like to find c which can be mapped as follow:

check_df = df.applymap(lambda in_each_cell_value: str(in_each_cell_value).find("c") >= 0)

The check_df returns the boolean values and locates the string in the cell. enter image description here

From the above 'check_df' you can extract and keep the column where the cell was found:

[column for column, count in check_df.sum().to_dict().items() 
     if count > 0]

Complete code:

df = pd.DataFrame([["a", "b", "c"], ["d", "e", "f"],["g", "h", "i"]])
check_df = df.applymap(lambda in_each_cell_value: str(in_each_cell_value).find("c") >= 0)
ind = [column for column, count in check_df.sum().to_dict().items() 
     if count > 0]

Outputs:

ind[0]
2

CodePudding user response:

Like this:

df[df[df.eq("c").any(1)].T.eq("c").any(1)].index[0]

2
  • Related