Brandon
Brandon

Reputation: 126

Replace values with values from other dataframe

I have two dataframes:

df1:

enter image description here

df2:

enter image description here

I'd like to update df2 with df1 values to create:

enter image description here

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

Answers (3)

Scott Boston
Scott Boston

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

Shubham Sharma
Shubham Sharma

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

BENY
BENY

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

Related Questions