首页 > 解决方案 > Pivoting of dataframe by year and month

问题描述

I have a data frame like this:

Factory Serial_number year  month   LT  Order  Minimum  Lot   Stock  Value 
    xxx       123     2020   8      20   123     456    10     2000    3000
    xxx       123     2020   9      ..   ...    ...     ..      ...    4000

Desired output is:

Factory Serial_number year  month  LT   Order   Minimum  Lot    Stock   8.2020  9.2020
  xxx       123       2020   8     20     123     456     10     2000    3000    4000

I tried different method like stacking, pivoting but that did not give the exact result

 pd.pivot_table(df, values='Value', index=['Factory', 'Serial_number','Order','Minimum Lot','Stock'],
                    columns=['year','month']).reset_index()

    Ouput I get: 


                                               

                                                        year           2020    
                   
                                                        month            8        9       10        11  12  1   2   3   4   5   6   7
                Factory 12NC    Order   Minimum Lot   Stock                                             
                xxx   1233     8430.0   305.0          10675.200  35295.86   38735.9    29546.91    23004.1 25433.2 0.0 13547.6 27095.2 0.0 2686             0.0    0.0 0.0
                      1234       660.0  330.0          108.000   0.00   0.0 0.00    0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
   

标签: pythonpandas

解决方案


推荐阅读