Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find which column contains a certain value?

I have a dataframe like this:

test = pd.DataFrame({"id":[1,2,3,4],
                     "name_1":["peter","bobby","alex","chris"],
                     "name_1_flag":["real","fake","fake","real"],
                     "name_2":["hector","abi","henrik","miko"],
                     "name_2_flag":["fake","real","fake","fake"],
                     "name_3":["hans","khan","will","than"],
                     "name_3_flag":["fake","fake","real","fake"]})

   id name_1 name_1_flag  name_2 name_2_flag name_3 name_3_flag
0   1  peter        real  hector        fake   hans        fake
1   2  bobby        fake     abi        real   khan        fake
2   3   alex        fake  henrik        fake   will        real
3   4  chris        real    miko        fake   than        fake

How can I find the row/column tuple that has the word "real" in it.

Optimally the output would be an array or series like this:

    col_index
0           3
1           5
2           7
3           3
like image 682
Baran Calisci Avatar asked Dec 30 '22 12:12

Baran Calisci


1 Answers

Use np.where:

test["col_index"] = np.where(test.eq("real"))[1] + 1
print(test)

Output

   id name_1 name_1_flag  name_2 name_2_flag name_3 name_3_flag  col_index
0   1  peter        real  hector        fake   hans        fake          3
1   2  bobby        fake     abi        real   khan        fake          5
2   3   alex        fake  henrik        fake   will        real          7
3   4  chris        real    miko        fake   than        fake          3
like image 136
Dani Mesejo Avatar answered Jan 04 '23 16:01

Dani Mesejo