3

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)

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

5 Comments

Alternate: df2.update(df1.rename(columns={'Last Accessed':'Date Accessed'})), +1
@Ch3steR Just a small note, update will only work if indices of both the dataframe matches ;)..
@ShubhamSharma Yes true good point, may be we can set Customer as index then update and reset index. Like your approach, +1.
@Ch3steR Why not undelete your solution, you had posted earlier.
@ShubhamSharma I didn't get a notification that you tagged me to undelete, did it now. ;) Thanks.
3

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

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.