Josef
Josef

Reputation: 2726

Search dataframe by multiple column values

This is my dataframe:

PERSON SUBJECT SCORE
0 A Math 7
1 A English 8
2 A Math 3
3 B English 9
4 B Art 3
5 C Math 3
6 C Art 3
7 C Chemistry 7

How to get student name if his Math score is 7 and English score is 8 (in this case that is student A)?

i've tried like this:

    data = {'PERSON': ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'C'],
                'SUBJECT': ['Math', 'English', 'Math', 'English', 'Art', 'Math', 'Art', 'Chemistry'],
                'SCORE' : [7, 8, 3, 9, 3, 3, 3, 7]
                }
    
df = pd.DataFrame(data, columns=['PERSON', 'SUBJECT', 'SCORE'])
    
st = df.loc[(df['SUBJECT'] == 'Math') & (df['SCORE'] == 7)]

This gives me

0 A Math 7

How to get only person which has subjects Math with score 7 and English with score 8?

Upvotes: 0

Views: 39

Answers (1)

Anna K
Anna K

Reputation: 111

Here's the solution I came up with:

df.set_index('PERSON', inplace=True)

st = df.loc[(df['SUBJECT'] == 'Math') & (df['SCORE'] == 7)]
st2 = df.loc[(df['SUBJECT'] == 'English') & (df['SCORE'] == 8)]

index1 = st.index
index2 = st2.index

if index1==index2:
    print(index1)
else:
    print("None")

Upvotes: 1

Related Questions