Use Pandas to merge two DataFrames

Viewed 52

I have two Pandas DataFrames below:

DataFrame1
   id  a comment
0   1  1     yes
1   2  2      no
2   3  3     yes
DataFrame2
   id  a
0   2  5
1   4  4

I'd like to update DataFrame1 with the contents of DataFrame2 based on the id column. Any new rows found in DataFrame2 not in DataFrame1 should be appended. The result should look like this:

DataFrame3
   id  a comment
0   1  1     yes
1   2  5      no
2   3  3     yes
3   4  4

I've tried using a mixture of DataFrame update/append/concat functions but can't quite get what I'm looking for. Any suggestions?

3 Answers

You can try concat then groupby:

pd.concat([df2,df1]).groupby('id', as_index=False).first()

Output:

   id  a comment
0   1  1     yes
1   2  5      no
2   3  3     yes
3   4  4     NaN

panda is a data display function, in python if the original data is in a dictionary you can mydict.update('key' : 'value') or mydict['key'] = value will also work. I think panda has a reverse function to get back the original dictionary. but I doubt that once it is in panda form that it can be manipulated as such. someone will let you know if this is wrong. I only use the panda data to display stuff because it is easy.

Pandas.DataFrame.merge should do it you can do database joins an update should work.

Related