簡體   English   中英

如何將列添加到 dataframe 中,其值取決於另一個 dataframe?

[英]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.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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM