0

I've a df1 that looks like (original one has over 1k rows):

   Invoice  Legal
0  153136   Quatro
1  202169   Rock
2  202129   Osiem
3  202119   Yetc

and a df2 that looks like:

   Legal    Org
0  Quatro   Sample
1  Osiem    Petra

I need to replace the column df1 Legal column with df2 Org data if the df2 Legal data is a match.

In this case would be (output):

   Invoice  Legal
0  153136   Sample -> changed
1  202169   Rock
2  202129   Petra  -> changed
3  202119   Yetc

I've tried the following, but I am getting an error. Thanks.

legal_dict = df2.set_index('Legal').to_dict()
df1['Legal'] = df1['Legal'].apply(lambda x: legal_dict[x])

Maybe worth to mention that the dfs are created via pd.read_csv

Gonzalo
  • 1,084
  • 4
  • 20
  • 40
  • 1
    `df1.Legal=df1.Legal.map(df2.set_index('Legal')['Org']).fillna(df1.Legal)` – anky Jul 25 '19 at 07:36
  • doesnt work, getting same error as below: File "pandas\_libs\hashtable_class_helper.pxi", line 1608, in pandas._libs.hashtable.PyObjectHashTable.get_item KeyError: 'Legal' – Gonzalo Jul 25 '19 at 08:00
  • that is a keyerror which means there is no columns named `Legal` , please check what is the column name in the original data in df1. also check if there are preceeding or succeeding spaces if it exists – anky Jul 25 '19 at 08:06

0 Answers0