将匹配的记录替换为pandas中下一列中的记录

时间:2018-03-11 04:00:49

标签: python pandas

我有两个数据框A,B

" A"数据框由1列(列名:str1)

组成

" B"数据框由2列组成(列名:m2,m3)

我正在比较来自" A"的str1。用于" B"

我想要的是" str1"匹配" m2"我想" str1"被" m3"取代。 以下是我的数据,

arrayId

我希望输出为

unsigned char arrayId[index]

所以A.str1与B.m1匹配时,A.str1将被B.m2取代 提前谢谢

1 个答案:

答案 0 :(得分:1)

我认为您需要创建助手Seriesreplace或使用map,但它会为非匹配列创建NaN,因此必须fillnacombine_first

df1 = pd.DataFrame({'str1': ["gmaps","facebook","gmail","linkedin"]})

df2 = pd.DataFrame({'m1': ["gmaps","oracle","gmail","intel"],
                    'm2': ["Google","xyz","Google","nvidia"]})

s = df2.set_index('m1')['m2']
print (s)
m1
gmaps     Google
oracle       xyz
gmail     Google
intel     nvidia
Name: m2, dtype: object

df1['str1'] = df1['str1'].replace(s)
#alternatives
#df1['str1'] = df1['str1'].map(s).fillna(df1['str1'])
#df1['str1'] = df1['str1'].map(s).combine_first(df1['str1'])
print (df1)

       str1
0    Google
1  facebook
2    Google
3  linkedin