新答案
这是一种基于pandas / numpy的方法。
rhs = (df1.column_common .apply(lambda x: df2[df2.column_common.str.find(x).ge(0)]['column_b']) .bfill(axis=1) .iloc[:, 0])(pd.concat([df1.column_a, rhs], axis=1, ignore_index=True) .rename(columns={0: 'column_a', 1: 'column_b'})) column_a column_b0 John Moore1 Michael Cohen2 Dan Smith3 George NaN4 Adam Faber旧答案
这是左联接行为的一种解决方案,因为它不会保留
column_a不匹配任何
column_b值的值。这比上面的numpy /
pandas解决方案要慢,因为它使用两个嵌套
iterrows循环来构建python列表。
tups = [(a1, a2) for i, (a1, b1) in df1.iterrows() for j, (a2, b2) in df2.iterrows() if b1 in b2](pd.Dataframe(tups, columns=['column_a', 'column_b']) .drop_duplicates('column_a') .reset_index(drop=True)) column_a column_b0 John Moore1 Michael Cohen2 Dan Smith3 Adam Faber


