1

Given a dataframe :

    Animal  wings   claws   horns
0   Ant     No      No      No
1   Bat     Yes     Yes     No
2   Cat     No      Yes     No

I am trying to print corresponding value of 'Animal' column where the value of given column is 'Yes'.

Eg1: Given column is 'claws', output should be Bat and Cat.

Eg2: Given column is 'wings', output should be Bat

Vinay Sharma
  • 319
  • 1
  • 5
  • 13

1 Answers1

3

You can filter each column separately - convert Animal to index by DataFrame.set_index and compare by DataFrame.eq, then filter by columns names and index convert to list:

df1 = df.set_index('Animal').eq('Yes')

print (df1.index[df1['wings']].tolist())
['Bat']
print (df1.index[df1['claws']].tolist())
['Bat', 'Cat']
print (df1.index[df1['horns']].tolist())
[]

Or is possible create dictionary use dict comprehension:

df1 = df.set_index('Animal').eq('Yes')

d = {col: df1.index[df1[col]].tolist() for col in df1}
print (d)
{'wings': ['Bat'], 'claws': ['Bat', 'Cat'], 'horns': []}

Or if want separator add join:

d1 = {col: ','.join(df1.index[df1[col]]) for col in df1}
print (d1)
{'wings': 'Bat', 'claws': 'Bat,Cat', 'horns': ''}

Or if want filter all columns to Series with index by Animal and values by all Yes values with separator , use DataFrame.dot with transpose DataFrame:

df1 = df.set_index('Animal').eq('Yes')
s = df1.T.dot(df1.index + ',').str.strip(',')
print (s)
wings        Bat
claws    Bat,Cat
horns           
dtype: object

print (s['wings'])
Bat
print (s['claws'])
Bat,Cat
print (s['horns'])
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252