简体   繁体   中英

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:

don't add friend

else:

add friend

Thank you!

if 'Mark' in list(df['Name']):
    print('Mark already in DF')
else:
    print('Mark not in DF')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM