Aragorn64
Aragorn64

Reputation: 129

Filter DataFrame Values

I have the following DataFrame:

Student food
1 R0100000
2 R0200000
3 R0300000
4 R0400000

I need to test if the Student = 1, a new "Selected_Food" string should be created with "R0100000" value. If the Student = 3, then the "Selected_Food" string should be contain the "R0300000" value and so on.

This is the code to create the same DataFrame as mine:

    data={'Student':[1,2,3,4],'food':['R0100000', 'R0200000', 'R0300000', 'R0400000']}
    df=pd.DataFrame(data)

The following code works for the first case , but it doesnt work if I change the Student value.

if(df.Student==1):
Selected_food=df.loc[0,"food"]

Upvotes: 0

Views: 17

Answers (1)

I'mahdi
I'mahdi

Reputation: 24049

You can check like below: (pandas.loc)

def func_chck(df, stu_num, food_slct):
    return (df.loc[df['Student'].eq(stu_num), 'food'] == food_slct).values[0]

>>> func_chck(df, 1, 'R0400000')
False

>>> func_chck(df, 1, 'R0100000')
True

Upvotes: 1

Related Questions