1

Say I have the following dataframe

data = [['Alex','Dog'],['Bob','Cat'],['Clarke','Giraffe']]
df = pd.DataFrame(data,columns=['Name','Age'])


+--------+---------+
|  Name  | Animal  |
+--------+---------+
| Alex   | Dog     |
| Bob    | Cat     |
| Clarke | Giraffe |
+--------+---------+

What is the most efficient way of getting the name of the column where the string Giraffe is found (i.e. Animal). We can assume there is only one of those string in the entire DataFrame.

notverygood
  • 297
  • 2
  • 13

1 Answers1

1

Definitely not the best/elegant answer but it does the trick

word = 'Giraffe'
df.columns[df[df==word].notna().sum()>0][0]

returns 'Animal' as a string.

This does only work if we assume there is only one column which can contain the word.

Hestaron
  • 190
  • 1
  • 8