1

I have two dataframes that I need to merge. However I would like to keep all the values in the columns. Assign column values from df2.Emotion to df1 where are similar words. And where these values are not found in df1, assign NaN.

Example

df1 = pd.DataFrame({
    'word': ['love', 'smile', 'happy', 'other'],
    'x': [0.113, 0.110, 0.711, 0.211],
    'y': [0.121, 0.131, 0.611, 0.181],
    'z': [0.121, 0.141, 0.511, 0.991]
})

# Assign the Emotion column to the df1 with similar words
df2 = pd.DataFrame({
    'word': ['smile', 'love', 'happy'],
    'emotion': ['friendly', 'joy', 'joy']
})

# Expected output
df_result = pd.DataFrame({
    'word': ['love', 'smile', 'happy', 'other'],
    'x': [0.113, 0.110, 0.711, 0.211],
    'y': [0.121, 0.131, 0.611, 0.181],
    'z': [0.121, 0.141, 0.511, 0.991],
    'emotion': ['joy', 'friendly', 'joy', float('NaN')]
})
Y4RD13
  • 937
  • 1
  • 16
  • 42
  • this is covered in our ubiquitous merging post: [Pandas Merging 101](https://stackoverflow.com/questions/53645882/pandas-merging-101) – cs95 Feb 13 '21 at 23:57
  • Please make sure to title pandas questions 'Pandas...' not 'Python...' So they get faster more accurate answers. – smci Feb 14 '21 at 06:24

1 Answers1

2

You can use merge with outer.

df1.merge(df2, how='outer')
Y4RD13
  • 937
  • 1
  • 16
  • 42