[英]How can I add a column to a dataframe with a value conditional on another dataframe?
I'm working with two dataframes:我正在使用两个数据框:
Dataframe1 looks like: Dataframe1 看起来像:
user (index)![]() |
apples![]() |
bananas![]() |
---|---|---|
Pete![]() |
4 ![]() |
2 ![]() |
Sara![]() |
5 ![]() |
10 ![]() |
Kara![]() |
4 ![]() |
2 ![]() |
Tom![]() |
3 ![]() |
3 ![]() |
Dataframe2 looks like: Dataframe2 看起来像:
index![]() |
user![]() |
---|---|
1 ![]() |
Pete![]() |
2 ![]() |
Sara![]() |
I want to create a new boolean column in dataframe1 that is true if the user is in dataframe 2. So output looks like:我想在 dataframe1 中创建一个新的 boolean 列,如果用户在 dataframe 2 中,这是真的。所以 output 看起来像:
user![]() |
apples![]() |
bananas![]() |
new column![]() |
---|---|---|---|
Pete![]() |
4 ![]() |
2 ![]() |
True![]() |
Sara![]() |
5 ![]() |
10 ![]() |
True![]() |
Kara![]() |
4 ![]() |
2 ![]() |
False![]() |
Tom![]() |
3 ![]() |
3 ![]() |
False![]() |
I tried using lambda function but didn't get very far.我尝试使用 lambda function 但没有走得很远。
Here is an easy way of doing that.这是一个简单的方法。
df = df.reset_index()
df2['new_column']=True
df = pd.merge(df, df2, left_on='user', right_on='user', how = 'left')
df.new_column.fillna(False, inplace=True)
You can leverage the indicator
param of df.merge
.您可以利用
df.merge
的indicator
参数。 Then use df.replace
:然后使用
df.replace
:
In [598]: x = df1.merge(df2['user'], left_on='user (index)', right_on='user', how='left', indicator='new column').replace({'both': True, 'left_only':False}).drop('user', 1)
In [599]: x
Out[599]:
user (index) apples bananas new column
0 Pete 4 2 True
1 Sara 5 10 True
2 Kara 4 2 False
3 Tom 3 3 False
OR:或者:
For some better performance, use Series.map
instead of df.replace
:为了获得更好的性能,请使用
Series.map
而不是df.replace
:
In [609]: y = df1.merge(df2['user'], left_on='user (index)', right_on='user', how='left', indicator='new column').drop('user', 1)
In [611]: y['new column'] = y['new column'].map({'both': True, 'left_only':False})
In [612]: y
Out[612]:
user (index) apples bananas new column
0 Pete 4 2 True
1 Sara 5 10 True
2 Kara 4 2 False
3 Tom 3 3 False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.