Krishna Prasad
Krishna Prasad

Reputation: 1

Python pandas selecting subset of dataframe using filter condition

I have a Pandas DataFrame as below

enter image description here I want to query on the columns to find out all the columns that contain 'X' for each Name.

sample output be like: (John, O, P) here O and P are the column ids against John that have the character 'X'. I tried query on Dataframe on columns using loc, but didn't get the output. please guide to get the required output.

Upvotes: 0

Views: 31

Answers (1)

Timeless
Timeless

Reputation: 37787

Here is a proposition using pandas.DataFrame.apply and dict to return a dictionnary where the keys are the person names and the values are the columns names that fulfill the condition (is equal to "X")

dico= dict(zip(df["Name"], df.eq("X").apply(lambda x: x.index[x].tolist(), axis=1)))

# Output :

print(dico)

{'John': ['O', 'P'], 'Dave': ['M', 'P']}

Upvotes: 1

Related Questions