Reputation: 249
I have 2 DataFrames:
city count school
0 New York 1 school_3
1 Washington 1 School_4
2 Washington 1 School_5
3 LA 1 School_1
4 LA 1 School_4
city count school
0 New York 1 School_3
1 Washington 1 School_1
2 LA 1 School_3
3 LA 2 School_4
I want to get the this result:
city count school
0 New York 2 school_3
1 Washington 1 School_1
2 Washington 1 School_4
3 Washington 1 School_5
4 LA 1 School_1
5 LA 1 School_3
6 LA 3 School_4
Following is the code.
d1 = [{'city':'New York', 'school':'school_3', 'count':1},
{'city':'Washington', 'school':'School_4', 'count':1},
{'city':'Washington', 'school':'School_5', 'count':1},
{'city':'LA', 'school':'School_1', 'count':1},
{'city':'LA', 'school':'School_4', 'count':1}]
d2 = [{'city':'New York', 'school':'School_3', 'count':1},
{'city':'Washington', 'school':'School_1', 'count':1},
{'city':'LA', 'school':'School_3', 'count':1},
{'city':'LA', 'school':'School_4', 'count':2}]
x1 = pd.DataFrame(d1)
x2 = pd.DataFrame(d2)
#just get empty DataFrame
print pd.merge(x1, x2)
How to get the aggregate result ?
Upvotes: 7
Views: 12178
Reputation: 5064
Here's a slightly different implementation from @elyase's solution using pandas.DataFrame.merge(...)
x1.merge(x2,on=['city', 'school', 'count'], how='outer').groupby(['city', 'school'], as_index=False)['count'].sum()
When timed in ipython notebook %timeit
this method is marginally faster than @elyase's (<1ms)
100 loops, best of 3: 6.25 ms per loop #using concat(...) with @elyase's solution
100 loops, best of 3: 5.49 ms per loop #using merge(...) in this solution
Also, if you want to use pandas aggregate
functionality you can also do:
x1.merge(x2,on=['city', 'school', 'count'], how='outer').groupby(['city', 'school'], as_index=False).agg(numpy.sum)
The only disclaimer is that using agg(...)
is the slowest of the 3 solutions.
Obviously all 3 provide the correct result:
city school count
0 LA School_1 1
1 LA School_3 1
2 LA School_4 3
3 New York School_3 1
4 New York school_3 1
5 Washington School_1 1
6 Washington School_4 1
7 Washington School_5 1
Upvotes: 5
Reputation: 40963
You can do:
>>> pd.concat([x1, x2]).groupby(["city", "school"], as_index=False)["count"].sum()
city school count
0 LA School_1 1
1 LA School_3 1
2 LA School_4 3
3 New York School_3 1
4 New York school_3 1
5 Washington School_1 1
6 Washington School_4 1
7 Washington School_5 1
Note that New York appears 2 times because of a typo in the data (school_3
vs School_3
).
Upvotes: 7