Alexis - 11 months ago 60
Python Question

How to look for a value in a Python DataFrame column?

This is my first question on this forum, sorry if my English is not so good!

I want to add a row to a DataFrame only if a specific column doesn't already contain a specific value. Let say I write this :

df = pd.DataFrame([['Mark', 9], ['Laura', 22]], columns=['Name', 'Age'])
new_friend = pd.DataFrame([['Alex', 23]], columns=['Name', 'Age'])
df = df.append(new_friend, ignore_index=True)
print(df)

Name  Age
0   Mark    9
1  Laura   22
2   Alex   23


Now I want to add another friend, but I want to make sure I don't already have a friend with the same name. Here is what I'm actually doing:

new_friend = pd.DataFrame([['Mark', 16]], columns=['Name', 'Age'])
df = df.append(new_friend, ignore_index=True)
print(df)

Name  Age
0   Mark    9
1  Laura   22
2   Alex   55
3   Mark   16


then :

df = df.drop_duplicates(subset='Name', keep='first')
df = df.reset_index(drop=True)
print(df)

Name  Age
0   Mark    9
1  Laura   22
2   Alex   55


Is there another way of doing this something like :

if name in Column 'Name'is True:

if 'Mark' in list(df['Name']):