I want to overwrite my df1.Name
values based on a mapping table in (df2.Name1, df2.Name2)
. However, not all values in df1.Name
exist in df2.Name1
Name
Alex
Maria
Marias
Pandas
Coala
Name1 Name2
Alex Alexs
Marias Maria
Coala Coalas
Name
Alexs
Maria
Maria
Pandas
Coalas
I have tried several solutions online such as using the Map function. By turning df2
in a Dictionary I am using df1.Name = df1.Name.map(Dictionary)
, but this will result in nan
for all values not in df2
as per below.
Name
Alexs
Maria
Maria
NAN
Coalas
I am not sure how to use an IF statement to replace only the ones that do exist in df2 and keep the rest as per df1.
I also tried to create a function with if
statements, but was big time failure.
How I could approach this problem?
In this article, we will learn how we can replace values of a DataFrame with the value of another DataFrame using pandas. It can be done using the DataFrame. replace() method. It is used to replace a regex, string, list, series, number, dictionary, etc.
You can replace values of all or selected columns based on the condition of pandas DataFrame by using DataFrame. loc[ ] property. The loc[] is used to access a group of rows and columns by label(s) or a boolean array. It can access and can also manipulate the values of pandas DataFrame.
replace() function is used to replace values in column (one value with another value on all columns). This method takes to_replace, value, inplace, limit, regex and method as parameters and returns a new DataFrame. When inplace=True is used, it replaces on existing DataFrame object and returns None value.
By using replace
df1.Name.replace(df2.set_index('Name1').Name2.to_dict())
Out[437]:
0 Alexs
1 Maria
2 Maria
3 Pandas
4 Coalas
Name: Name, dtype: object
Let's use a Pandas solution with map
and combine_first
:
df1['Name'].map(df2.set_index('Name1')['Name2']).combine_first(df1['Name'])
Output:
0 Alexs
1 Maria
2 Maria
3 Pandas
4 Coalas
Name: Name, dtype: object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With