Pandas_Pivot table - making additional columns from division of merged columns

此生再无相见时 提交于 2019-12-23 04:16:07

问题


I'm trying to run the following function

def make_europe_view(data):

    data['% Rev'] = data.GrossRevenue_GBP/data.GrossRevenue_GBP.sum()

    tmean = lambda x :stats.trim_mean(x, 0.1)

    pivot = pd.pivot_table(data[(data['New_category_ID'] != 0)&(data['YYYY'] == 2016)], 
                                index = 'New_category',  
                                values=['GrossRevenue_GBP','MOVC_GBP','PM_GBP', '% Rev'],
                                aggfunc= {'MOVC_GBP':tmean,'PM_GBP':tmean,'GrossRevenue_GBP':[np.sum,tmean],'% Rev':np.sum })



    pivot['% PM'] = pivot['PM_GBP']/pivot[('GrossRevenue_GBP')]['<lambda>']
    #pivot['% MOVC'] = pivot['MOVC_GBP']/Tmean_GR
    pivot['Country'] = 'EU'
    pivot['product_cat'] = pivot.index

    #pivot = pivot[['product_cat', '% Rev', 'GrossRevenue_GBP', 'MOVC_GBP', 'PM_GBP', '% PM', '% MOVC', 'Country']]

    return pivot

I want to aggregate Gross Revenue by truncated mean and sum, I have no issue generating the pivot table however I am experiencing issues when it comes to create some additional columns. Specifically this part of the code:

 pivot['% PM'] = pivot['PM_GBP']/pivot[('GrossRevenue_GBP')]['<lambda>']

I am trying to create a column that will calculated % truncated mean of PM by taking the truncated mean of 'PM_GBP' column as a percentage of the truncated mean of 'GrossRevenue_GBP' column

It generates the following error:

ValueError: Wrong number of items passed 25, placement implies 1

Would really appreciate some help with this.

column names for pivot when I run list():

[('GrossRevenue_GBP', '<lambda>'),  ('GrossRevenue_GBP', 'sum'),  ('% Rev', 'sum'),  ('MOVC_GBP', '<lambda>'),  ('PM_GBP', '<lambda>'),  ('Country', ''),  ('product_cat', '')]

回答1:


You can use tuples for select values in MultiIndex in columns:

tups = [('GrossRevenue_GBP', '<lambda>'),  ('GrossRevenue_GBP', 'sum'),  ('% Rev', 'sum'),  ('MOVC_GBP', '<lambda>'),  ('PM_GBP', '<lambda>'),  ('Country', ''),  ('product_cat', '')]
idx = list('ab')
cols = pd.MultiIndex.from_tuples(tups)
pivot = pd.DataFrame([[7,4,5,8,4,5,1],
                   [1,5,7,3,9,6,7]], columns=cols, index=idx)
print (pivot)
  GrossRevenue_GBP     % Rev MOVC_GBP   PM_GBP Country product_cat
          <lambda> sum   sum <lambda> <lambda>                    
a                7   4     5        8        4       5           1
b                1   5     7        3        9       6           7

pivot['% PM'] = pivot[('PM_GBP','<lambda>')]/pivot[('GrossRevenue_GBP','<lambda>')]
print (pivot)
  GrossRevenue_GBP     % Rev MOVC_GBP   PM_GBP Country product_cat      % PM
          <lambda> sum   sum <lambda> <lambda>                              
a                7   4     5        8        4       5           1  0.571429
b                1   5     7        3        9       6           7  9.000000

For simplier life is possible remove MultiIndex and create columns:

#rename columns by dict
pivot = pivot.rename(columns={'<lambda>':'tmean'})
#remove multiindex
pivot.columns = pivot.columns.map('_'.join).str.strip('_')

#simply divide
pivot['% PM'] = pivot['PM_GBP_tmean']/pivot['GrossRevenue_GBP_tmean']
print (pivot)
   GrossRevenue_GBP_tmean  GrossRevenue_GBP_sum  % Rev_sum  MOVC_GBP_tmean  \
a                       7                     4          5               8   
b                       1                     5          7               3   

   PM_GBP_tmean  Country  product_cat      % PM  
a             4        5            1  0.571429  
b             9        6            7  9.000000  


来源:https://stackoverflow.com/questions/45632484/pandas-pivot-table-making-additional-columns-from-division-of-merged-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!