I am trying to merge two tables such as: df1:
| ID |
|---|
| A1A1A1 |
| A1A1A2 |
| B1B1B1 |
df2:
| ID | Country |
|---|---|
| A1A1A1 | France |
| B | Egypt |
| C1C | Egypt |
In Table 2, when the ID = B, it means that all IDs starting with B will have the same country. The same applies to ID = CCC1 Hence, I cannot use pd.merge as I cannot merge on an exact match. I have written a code that seems to work (using debug) but that is incredibly slow. I am looking therefore for faster solution. My df1 has ~80K rows, df2 has ~7K rows.
Expected Output: df2:
| ID | Country |
|---|---|
| A1A1A1 | France |
| A1A1A2 | nan |
| B1B1B1 | Egypt |
Here is what I did:
for i in range(len(df2)):
for j in range(len(df1)):
if df1['ID'].iloc[j].startswith(df2['ID'].iloc[i]):
df1['Country'].iloc[j] = df2['Country'].iloc[i]
Thanks!