I have two dataframe that I want to merge based on a partial match of start with (rows in df2.B that start with df1.A in the example below and the values of these columns are strings, which could be of any length).
I can do that the following way, but it is very slow on my actual dataframes, which have millions of rows each.
df1 = pd.DataFrame({'A': ['a', 'b', 'cc']})
df2 = pd.DataFrame({'B': ['ar', 'd', 'ar'],
'C': ['x1', 'x1', 'x2']})
df_m = pd.DataFrame(columns=['A','B','C'])
for index, row in df1.iterrows():
df_ = df2[df2['B'].str.startswith(row['A'])]
if not df_.empty:
df_['A'] = row['A']
df_m = df_m.append(df_)
df_m:
A B C
0 a ar x1
2 a ar x2