【问题标题】:How can I add a column to a dataframe with a value conditional on another dataframe?如何将列添加到具有以另一个数据框为条件的值的数据框?
【发布时间】:2020-12-13 15:38:33
【问题描述】:

我正在使用两个数据框:

Dataframe1 看起来像:

user (index) apples bananas
Pete 4 2
Sara 5 10
Kara 4 2
Tom 3 3

Dataframe2 看起来像:

index user
1 Pete
2 Sara

我想在 dataframe1 中创建一个新的布尔列,如果用户在 dataframe 2 中,则该列为 true。所以输出如下所示:

user apples bananas new column
Pete 4 2 True
Sara 5 10 True
Kara 4 2 False
Tom 3 3 False

我尝试使用 lambda 函数,但没有走多远。

【问题讨论】:

  • 为什么不使用df1['new column'] = df1['user (index)'].isin(df2['user'])

标签: python pandas


【解决方案1】:

这是一个简单的方法。

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)

【讨论】:

    【解决方案2】:

    您可以利用df.mergeindicator 参数。然后使用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多