Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merge few pivot tables in pandas

How I can merge two pandas pivot tables? When I try run my code I have error: keyerror

data_pivot= pandas.DataFrame(data.pivot_table(values = 'NR_ACTIONS', index=["HOUR", "OPID", "NAME"], columns='CONTACTED_PERSON_NEW', aggfunc='sum'))
data_pivot.fillna(0, inplace=True)
data2_pivot= pandas.DataFrame(data2.pivot_table(values = 'AMOUNT_PA', index=["HOUR", "OPID", "NAME"], columns='PA_TYPE', aggfunc='sum'))
data2_pivot.fillna(0, inplace=True)
all_data = pandas.merge(data_pivot, data2_pivot, 'left', on = ["HOUR", "OPID", "NAME"] ) 
like image 235
K.Palyanichka Avatar asked Aug 19 '15 09:08

K.Palyanichka


People also ask

Can you merge multiple DataFrames in pandas at once?

Pandas' merge and concat can be used to combine subsets of a DataFrame, or even data from different files. join function combines DataFrames based on index or column. Joining two DataFrames can be done in multiple ways (left, right, and inner) depending on what data must be in the final DataFrame.

How do I merge multiple DataFrames in pandas?

Just simply merge with DATE as the index and merge using OUTER method (to get all the data). Now, basically load all the files you have as data frame into a list. And, then merge the files using merge or reduce function.

How do I merge multiple columns in pandas?

To merge two pandas DataFrames on multiple columns use pandas. merge() method. merge() is considered more versatile and flexible and we also have the same method in DataFrame.


1 Answers

answer for my question is :

data_pivot= pandas.DataFrame(data.pivot_table(values = 'NR_ACTIONS', index=["HOUR", "OPID", "NAME"], columns='CONTACTED_PERSON_NEW', aggfunc='sum'))
data_pivot.fillna(0, inplace=True)
data_pivot.reset_index( inplace=True)
data2_pivot= pandas.DataFrame(data2.pivot_table(values = 'AMOUNT_PA', index=["HOUR", "OPID", "NAME"], columns='PA_TYPE', aggfunc='sum'))
data2_pivot.fillna(0, inplace=True)
data2_pivot.reset_index( inplace=True)
all_data = pandas.merge(data_pivot, data2_pivot, 'left', on = ["HOUR", "OPID", "NAME"] )
like image 124
K.Palyanichka Avatar answered Sep 28 '22 16:09

K.Palyanichka