Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
merge dataframes
#1
Hi,

I need to merge this two dataframes:

df1
pais   año  cantidad
 0  Chile  2000        10
 1  Chile  2001        11
 2  Chile  2002        12
df2
pais   año  cantidad
 0  Chile  1999         0
 1  Chile  2000         0
 2  Chile  2001         0
 3  Chile  2002         0
 4  Chile  2003         0
Right now I'm trying this code:

df=pd.merge(df1,df2,on=['pais','año','cantidad'],how='outer')
And getting this result:

pais 	año 	cantidad
0 	Chile 	2000 	10
1 	Chile 	2001 	11
2 	Chile 	2002 	12
3 	Chile 	1999 	0
4 	Chile 	2000 	0
5 	Chile 	2001 	0
6 	Chile 	2002 	0
7 	Chile 	2003 	0
Which is the simply union of both df's. I need something that produces this result:

pais 	año 	cantidad
0   Chile   1999  0
1 	Chile 	2000 	10
2 	Chile 	2001 	11
3 	Chile 	2002 	12
4 	Chile 	2002 	0
5 	Chile 	2003 	0
Any ideas? Thank!!
Reply
#2
Hope this helps;
df1 = pd.DataFrame(data = {'pais':['Chile','Chile','Chile'],
                             'año':[2000,2001,2002],
                             'cantidad':[10,11,12],})
    
df2 = pd.DataFrame(data = {'pais':['Chile','Chile','Chile','Chile','Chile'],
                             'año':[1999,2000,2001,2002,2003],
                             'cantidad':[0,0,0,0,0],})

df1=df1.set_index(['pais','año'])
df2=df2.set_index(['pais','año'])    

df1_2 = df1.add(df2,fill_value=0)
df1_2.reset_index()
Output:
Out[280]: pais año cantidad 0 Chile 1999 0.0 1 Chile 2000 10.0 2 Chile 2001 11.0 3 Chile 2002 12.0 4 Chile 2003 0.0
jefsummers likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  merge two dataframes with different number of rows dawid294 5 4,043 Feb-05-2021, 03:21 PM
Last Post: perfringo
  How to merge three DataFrames based on specific column Mekala 0 1,789 Sep-08-2020, 02:01 PM
Last Post: Mekala
  Merge 2 dataframes but avoid double summing of rows? vinaysalian17 0 1,846 Jun-03-2020, 01:48 AM
Last Post: vinaysalian17

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020