![](/img/trans.png)
[英]How can i add a column to a dataframe based on a conditional of another dataframe that has a different length, but shared column data
[英]How can I add a column to a dataframe with a value conditional on another dataframe?
我正在使用两个数据框:
Dataframe1 看起来像:
用户(索引) | 苹果 | 香蕉 |
---|---|---|
皮特 | 4 | 2 |
萨拉 | 5 | 10 |
卡拉 | 4 | 2 |
汤姆 | 3 | 3 |
Dataframe2 看起来像:
指数 | 用户 |
---|---|
1 | 皮特 |
2 | 萨拉 |
我想在 dataframe1 中创建一个新的 boolean 列,如果用户在 dataframe 2 中,这是真的。所以 output 看起来像:
用户 | 苹果 | 香蕉 | 新专栏 |
---|---|---|---|
皮特 | 4 | 2 | 真的 |
萨拉 | 5 | 10 | 真的 |
卡拉 | 4 | 2 | 错误的 |
汤姆 | 3 | 3 | 错误的 |
我尝试使用 lambda function 但没有走得很远。
这是一个简单的方法。
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)
您可以利用df.merge
的indicator
参数。 然后使用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
或者:
为了获得更好的性能,请使用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.