Reputation: 126
I have two dataframes:
df1:
df2:
I'd like to update df2 with df1 values to create:
Code to generate example dataframes below:
import pandas as pd
test_dict = {'Customer': ['A', 'B', 'C'], 'Last Accessed': ['7/16/2020','7/5/2020', '7/1/2020']}
df1 = pd.DataFrame.from_dict(test_dict)
test_dict = {'Customer': ['A', 'B', 'C', 'D', 'E', 'F'], 'Date Accessed': ['5/15/2020','5/15/2020', '5/15/2020', '5/15/2020', '5/15/2020', '5/15/2020']}
df2 = pd.DataFrame.from_dict(test_dict)
Upvotes: 3
Views: 53
Reputation: 153510
You can use combine_first
after rename
column.
df1.rename(columns={'Last Accessed':'Date Accessed'}).combine_first(df2)
Output:
Customer Date Accessed
0 A 7/16/2020
1 B 7/5/2020
2 C 7/1/2020
3 D 5/15/2020
4 E 5/15/2020
5 F 5/15/2020
Upvotes: 3
Reputation: 71707
Use merge
+ fillna
:
df = df2.merge(df1, on='Customer', how='left')
df['Date Accessed'] = df.pop('Last Accessed').fillna(d['Date Accessed'])
Result:
Customer Date Accessed
0 A 7/16/2020
1 B 7/5/2020
2 C 7/1/2020
3 D 5/15/2020
4 E 5/15/2020
5 F 5/15/2020
Upvotes: 3
Reputation: 323366
Let us try concat
then drop_duplicates
df = pd.concat([df1.rename(columns={'Last Accessed':'Date Accessed'}),df2]).drop_duplicates('Customer')
Out[81]:
Customer Date Accessed
0 A 7/16/2020
1 B 7/5/2020
2 C 7/1/2020
3 D 5/15/2020
4 E 5/15/2020
5 F 5/15/2020
Upvotes: 3