'Panda print the mark if the name exists

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!



Solution 1:[1]

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

Solution 2:[2]

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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mozway
Solution 2 sophocles