[英]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. 我只想在特定列尚未包含特定值的情况下向DataFrame添加行。 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: 如果“名称”列中的名称为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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.