如果 df1 滿足 df2 兩列中的兩個條件,我想在 df1 中創建一個新的布爾列。例如:df1: ID Date01234 8-23-202001234 8-26-202001235 8-24-202001235 9-3-202001236 9-1-2020df2: id visit01234 8-23-202001235 9-3-2020我想在 df1 中僅將 df2 中的訪問設置為“True”,結果如下:df1: ID Date In_store01234 8-23-2020 101234 8-26-2020 001235 8-24-2020 001235 9-3-2020 101236 9-1-2020 0我試過了:pos_id = df2['id'].tolist()pos_date = df2['visit'].tolist()for row in df: if df1['ID'].isin(pos_id) and df1['Date'].isin(pos_visit): df1['In_store'] = 1 else: df1['In_store'] = 0但我得到:“ValueError:系列的真值不明確。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()?!蔽乙呀泧L試過:for row in df: if df1['ID'] == df2['ID'] and df1['Date'] == df2['Date']: df1['In_store'] = 1 else: df1['In_store'] = 0但我得到:“ValueError:只能比較相同標簽的系列對象”,即使將列重命名為相同的列后也是如此。我缺少什么?謝謝
1 回答

阿波羅的戰車
TA貢獻1862條經驗 獲得超6個贊
這本質上是合并:
merged = df1.merge(df2, left_on=['ID','Date'], right_on=['id','visit'], how='left')
df1['In_store'] = merged['visit'].notna().astype(int)
輸出:
ID Date In_store
0 1234 8-23-2020 1
1 1234 8-26-2020 0
2 1235 8-24-2020 0
3 1235 9-3-2020 1
4 1236 9-1-2020 0
添加回答
舉報
0/150
提交
取消