如何在熊猫中的数据透视表中聚合

时间:2018-12-17 08:11:46

标签: python 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

我想要的数据框是

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 

我正在熊猫里追随。

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

但是,这没有给我我想要的输出。

2 个答案:

答案 0 :(得分:2)

pivot_table中的默认聚合函数为np.mean,因此有必要将其更改为sum,然后在列表理解中展平MultiIndex

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  

答案 1 :(得分:0)

我在熊猫中使用的数据透视表很少,但是您可以使用groupby和一些重塑来获得结果。

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

这些列将是您可能要重命名的MultiIndex。

相关问题