简体   繁体   中英

how to aggregate in pivot table in pandas

I have following dataframe in pandas

   code     date         tank      nozzle       qty      amount
   123      2018-01-01   1         1            100      0
   123      2018-01-01   1         2            0        50
   123      2018-01-01   1         2            0        50
   123      2018-01-01   1         2            100      0 
   123      2018-01-02   1         1            0        70
   123      2018-01-02   1         1            0        50
   123      2018-01-02   1         2            100      0

My desired dataframe is

code   date       tank     nozzle_1_qty   nozzle_2_qty  nozzle_1_amount   nozzle_2_amount
123   2018-01-01  1        100             100          0                 100
123   2018-01-02  1        0               100          120               0 

I am doing following in pandas..

df= (df.pivot_table(index=['date', 'tank'], columns='nozzle',
                     values=['qty','amount']).add_prefix('nozzle_')
         .reset_index()
      )

But,this does not give me my desired output.

Default aggregation function in pivot_table is np.mean , so is necessary change it to sum and then flatten MultiIndex in list comprehension:

df = df.pivot_table(index=['code','date', 'tank'], 
                    columns='nozzle', 
                    values=['qty','amount'], aggfunc='sum')
#python 3.6+
df.columns = [f'nozzle_{b}_{a}' for a, b in df.columns]
#python bellow
#df.columns = ['nozzle_{}_{}'.format(b,a) for a, b in df.columns]
df = df.reset_index()
print (df)
   code        date  tank  nozzle_1_amount  nozzle_2_amount  nozzle_1_qty  \
0   123  2018-01-01     1                0              100           100   
1   123  2018-01-02     1              120                0             0   

   nozzle_2_qty  
0           100  
1           100  

I don't use pivot_table much in pandas, but you can get your result using groupby and some reshaping.

df = df.groupby(['code', 'date', 'tank', 'nozzle']).sum().unstack()

The columns will be a MultiIndex that you maybe want to rename.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM