Skip to content Skip to sidebar Skip to footer

Adding Dates (series) Column From One Dataframe To The Other Pandas, Python

I am trying to 'broadcast' a date column from df1 to df2. In df1 I have the names of all the users and their basic information. In df2 I have a list of purchases made by the use

Solution 1:

I think you need merge with subset [['Name','DoB']] - need Name column for matching:

print (df1[['Name','DoB']])
    Name        DoB
0   John 2012-01-041   Jack 1991-02-032  Wendy 1986-10-043   Paul 1985-03-06

df2 = df2.merge(df1[['Name','DoB']], on='Name', how='left')
print (df2)
    Name        Purchase        DoB
0   John          fridge 2012-01-041  Wendy          coffee 1986-10-042   John  washingmachine 2012-01-043   Jack         tickets 1991-02-034  Wendy          iPhone 1986-10-045   Jack           stove 1991-02-036   John        notebook 2012-01-047   John          laptop 2012-01-04

Another solution with map by Series s:

s=df1.set_index('Name')['DoB']print(s)NameJohn2012-01-04Jack1991-02-03Wendy1986-10-04Paul1985-03-06Name:DoB,dtype:datetime64[ns]df2['DoB']=df2.Name.map(s)print(df2)NamePurchaseDoB0Johnfridge2012-01-041Wendycoffee1986-10-042Johnwashingmachine2012-01-043Jacktickets1991-02-034WendyiPhone1986-10-045Jackstove1991-02-036Johnnotebook2012-01-047Johnlaptop2012-01-04

Post a Comment for "Adding Dates (series) Column From One Dataframe To The Other Pandas, Python"