Python 2.7 输入与两个数据帧中的两列匹配的数据帧
我有一个数据帧Python 2.7 输入与两个数据帧中的两列匹配的数据帧,python-2.7,pandas,dataframe,Python 2.7,Pandas,Dataframe,我有一个数据帧C和另一个数据帧S。如果C和S中的两列具有相同的值,我想更改C的其中一列中的值 请考虑下面给出的例子, C.head(3) id1 id2 title val 0 1 0 'abc' 0 1 2 0 'bcd' 0 2 3 0 'efg' 0 S.head(3) id1 id2 0 1 1 1 3 0 我想将值1赋给C中的列“val”,该列仅
C
和另一个数据帧S
。如果C
和S
中的两列具有相同的值,我想更改C
的其中一列中的值
请考虑下面给出的例子,
C.head(3)
id1 id2 title val
0 1 0 'abc' 0
1 2 0 'bcd' 0
2 3 0 'efg' 0
S.head(3)
id1 id2
0 1 1
1 3 0
我想将值1赋给C中的列“val”,该列仅对应于C.id1=S.id1和C.id2=S.id2的行
(C.id1,C.id2)和(S.id1,S.id2)的组合在各自的表中是唯一的
在上述情况下,我希望结果如下
C.head(3)
id1 id2 title val
0 1 0 'abc' 0
1 2 0 'bcd' 0
2 3 0 'efg' 1
由于仅在C
的第三行中,它与S
的一行中的id1
和id2
列匹配,我认为需要使用左连接和参数指示器
,最后将boolen掩码转换为0
和1
:
#if same columns for join in both df parameter on is possible omit
df = C.merge(S, indicator=True, how='left')
#if multiple same columns in both df
#df = C.merge(S, indicator=True, how='left', on=['id1', 'id2'])
df['val'] = (df['_merge'] == 'both').astype(int)
df = df.drop('_merge', axis=1)
print (df)
id1 id2 val
0 1 0 0
1 2 0 0
2 3 0 1
解决方案很好地处理新数据:
df = C.merge(S, indicator=True, how='left')
#if multiple same columns in both df
#df = C.merge(S, indicator=True, how='left', on=['id1', 'id2'])
df['val'] = (df['_merge'] == 'both').astype(int)
df = df.drop('_merge', axis=1)
print (df)
id1 id2 title val
0 1 0 abc 0
1 2 0 bcd 0
2 3 0 efg 1
我编辑了一个问题,指出
C
将包含不在S
中的额外列