Home > OS >  Panda print the mark if the name exists
Panda print the mark if the name exists

Time:04-12

Name Mark
Ben 20
James 50
Jimmy 70

I have a dataframe which looks something like this. I wanna check if the name exists and then it will print the mark for that specific person.

if len(df[(df['Name'] == "James")]) != 0:
    print(len(df["Mark"]))

Above is my code. Hope to get some advise!

CodePudding user response:

You can return the mark of a specified name in your Name column using loc. The below will print the Mark of the name you pass, and will return an empty series if the name does not exist in your Name column:

name_to_retrieve_mark = 'Ben'
df.loc[df.Name.eq(name_to_retrieve_mark),'Mark']

Out[13]: 
0    20
Name: Mark, dtype: int64

name_to_retrieve_mark = 'Sophocles'
df.loc[df.Name.eq(name_to_retrieve_mark),'Mark']

Out[15]: Series([], Name: Mark, dtype: int64)

CodePudding user response:

Better use a Series here with get with a default argument:

marks = df.set_index('Name')['Mark']

marks.get('James', 'missing')
# 50

marks.get('Nonexistent', 'missing')
# missing

Or without default, get returns None:

marks.get('Nonexistent') # no output
  • Related