假设我有两个数据帧 df1 和 df2。
如果 df1 的特定列的值包含 df2 的特定列中的字符串,我想将 df2 的一些列附加到 df1,如果不是,则为 NaN。
一个小例子:
import pandas as pd
df1 = pd.DataFrame({'col': ['abc', 'def', 'abg', 'xyz']})
df2 = pd.DataFrame({'col1': ['ab', 'ef'], 'col2': ['match1', 'match2'], 'col3': [1, 2]})
df1:
col
0 abc
1 def
2 abg
3 xyz
df2:
col1 col2 col3
0 ab match1 1
1 ef match2 2
I want:
col col2_match col3_match
0 abc match1 1
1 def match2 2
2 abg match1 1
3 xyz NaN NaN
我设法以一种肮脏且低效的方式做到这一点,但就我而言, df1 包含大约 100K 行,并且需要很长时间......
提前致谢 !
EDIT
有点脏,但工作完成得相对较快(不过我仍然认为存在一种最聪明的方法......):
import pandas as pd
import numpy as np
df1 = pd.DataFrame({'col': ['abc', 'def', 'abg']})
df2 = pd.DataFrame({'col1': ['ab', 'ef'],
'col2': ['match1', 'match2'],
'col3': [1, 2]})
def return_nan(tup):
return(np.nan if len(tup[0]) == 0 else tup[0][0])
def get_indexes_match(l1, l2):
return([return_nan(np.where([x in e for x in l2])) for e in l1])
def merge(df1, df2, left_on, right_on):
df1.loc[:, 'idx'] = get_indexes_match(df1[left_on].values,
df2[right_on].values)
df2.loc[:, 'idx'] = np.arange(len(df2))
return(pd.merge(df1, df2, how='left', on='idx'))
merge(df1, df2, left_on='col', right_on='col1')