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"] )
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.
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.
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.
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"] )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With