Replace A Value In A Dataframe With A Value From Another Dataframe
I have a replacing problem in python. I'm trying to replace all the integer value in the column ORIGIN_AIRPORT from df_2 with the IATA column from df_1. The key-columns are ORIGIN_
Solution 1:
I am going to write the simplest solution for this :
Step 1: Convert both columns from df_1 into a dictionary by using the following code:
d = dict(zip(df_1.ID,df_1.IATA))
Step 2: Now we just need to map this dictionary and df_2:
df_2.ORIGIN_AIRPORT= df_1.ID.map(d)
Solution 2:
You can do a left join of df_1
and df_2
.
Given the moderate size of df1
, you can just create a mapping rule:
mapping = {}
for row in df_1.iterrows():
mapping[row[0]] = row[1]
And create a new column:
df2['AIRPORT_PROCESSED'] = df2['ORIGIN_AIRPORT'].apply(lambda x: mapping.get(x, x))
The last function will replace ORIGIN_AIRPORT
value for the value from mapping if x
is in mapping
.
Post a Comment for "Replace A Value In A Dataframe With A Value From Another Dataframe"