python - Pandas: subtract one column from another in a pivot table -


i subtract 1 columns in pivot table. 'diff' shoud difference between 2017 , 2016

raw_data = {'year': [2016,2016,2017,2017],     'area': ['a','b','a','b'],     'age': [10,12,50,52]} df1 = pd.dataframe(raw_data, columns = ['year','area','age'])  table=pd.pivot_table(df1,index=['area'],columns=['year'],values['age'],aggfunc='mean')  table['diff']=table['2017']-table['2016'] 

you need remove [] in pivot_table dont create multiindex in columns:

table=pd.pivot_table(df1,index='area',columns='year',values='age',aggfunc='mean') print (table) year  2016  2017 area                   10    50 b       12    52  table['diff']=table[2017]-table[2016] print (table) year  2016  2017  diff area                         10    50    40 b       12    52    40 

another possible solution droplevel:

table=pd.pivot_table(df1,index=['area'],columns=['year'],values=['age'],aggfunc='mean') table.columns = table.columns.droplevel(0) print (table) year  2016  2017 area                   10    50 b       12    52 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -