Reputation: 307
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.
Upvotes: 1
Views: 277
Reputation: 302
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.
Upvotes: 1