熊猫只为带有另一个表的常见行设置列值

时间:2018-08-10 08:13:29

标签: pandas

输入

table 1

+---+---+---+
| A | B | C |
+---+---+---+
| a | b | 0 |
+---+---+---+
| x | y | 0 |
+---+---+---+
| w | q | 0 |
+---+---+---+

table 2
+---+---+
| A | B |
+---+---+
| a | b |
+---+---+
| w | q |
+---+---+

输出

table 1

+---+---+---+
| A | B | C |
+---+---+---+
| a | b | 1 | <-
+---+---+---+
| x | y | 0 |
+---+---+---+
| w | q | 1 | <-
+---+---+---+

我有两个表,我想将表1中所有与表2中的行具有相同值的行的表1中的C列设置为1。

1 个答案:

答案 0 :(得分:2)

使用

In [303]: df1['C'] = df1.merge(df2, how='left', indicator='_')['_'].eq('both').astype(int)

In [304]: df1
Out[304]:
   A  B  C
0  a  b  1
1  x  y  0
2  w  q  1