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

1
  • Sorry, for first look it seems like dupe. Commented Feb 7, 2020 at 12:32

1 Answer 1

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'])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.