测试不同列中值的存在

时间:2019-05-29 08:10:59

标签: python pandas dataframe left-join

我要搜索等于id1或id2的列ID,然后在F1中添加值为col3的列。还有NAN。

   d = {'id1': ["ABC","ANB","ATB","BTP"],'id2':["XXX","YYY","ZZZ","TTT"], 'Name': ["A1","A2","A3","A4"]}
   F1 = pd.DataFrame(data=d)
   d = {'id': ["ABC","ANB","ZZZ"], 'col3': [0,1,1]}
   F2 = pd.DataFrame(data=d)

我做了这行代码,但是没有给出预期的结果。

 pd.concat([F1.merge(F2, left_on='id1', right_on='id'),F1.merge(F2, left_on='id2', right_on='id')], axis=0).drop(['Name','id'], axis=1)

预期输出如下图所示。enter image description here

1 个答案:

答案 0 :(得分:1)

Series.mapDataFrame.set_index创建的Series的两列都使用双Series.fillna,以替换缺失的值:

s = F2.set_index('id')['col3']
F1['col3'] = F1['id1'].map(s).fillna(F1['id2'].map(s))
print (F1)
   id1  id2 Name  col3
0  ABC  XXX   A1   0.0
1  ANB  YYY   A2   1.0
2  ATB  ZZZ   A3   1.0
3  BTP  TTT   A4   NaN

详细信息

print (F1['id1'].map(s))
0    0.0
1    1.0
2    NaN
3    NaN
Name: id1, dtype: float64

print (F1['id2'].map(s))
0    NaN
1    NaN
2    1.0
3    NaN
Name: id2, dtype: float64

print(F1['id1'].map(s).fillna(F1['id2'].map(s)))
0    0.0
1    1.0
2    1.0
3    NaN
Name: id1, dtype: float64

您的解决方案应使用左联接和fillna进行更改:

a = F1.merge(F2, left_on='id1', right_on='id', how='left')['col3']
b = F1.merge(F2, left_on='id2', right_on='id', how='left')['col3']

F1['col3'] = a.fillna(b)
print (F1)
   id1  id2 Name  col3
0  ABC  XXX   A1   0.0
1  ANB  YYY   A2   1.0
2  ATB  ZZZ   A3   1.0
3  BTP  TTT   A4   NaN

如果最后一列中需要整数,则最后一个需要使用Int64进行转换的熊猫0.24 +:

F1['col3'] = F1['id1'].astype('Int64')
print (F1)
   id1  id2 Name  col3
0  ABC  XXX   A1     0
1  ANB  YYY   A2     1
2  ATB  ZZZ   A3     1
3  BTP  TTT   A4   NaN