简体   繁体   中英

Pivot table returns a key error in Pandas

I have a dataframe called performanceData that looks like:

                         id  settle_price  settle_price_acc     pos    trade  \
date                                                                           
2016-01-04  BBG.XTKS.9716.S     14.096973         14.096973  8100.0  -1700.0   
2016-01-04  BBG.XTKS.9065.S      4.460498          4.460498  4000.0  20000.0   
2016-01-04  BBG.XTKS.7966.S     17.599029         17.599029  -500.0  27700.0   
2016-01-04  BBG.XTKS.3774.S     19.514999         19.514999     0.0    200.0   
2016-01-04  BBG.XTKS.5110.S     15.143828         15.143828  -200.0      0.0   

            nominal_posn_size  abs_nominal_posn_size  abs_nominal_trade_size  
date                                                                          
2016-01-04      114185.481138          114185.481138            23964.854066  
2016-01-04       17841.990960           17841.990960            89209.954800  
2016-01-04       -8799.514730            8799.514730           487493.116042  
2016-01-04           0.000000               0.000000             3902.999806  
2016-01-04       -3028.765682            3028.765682                0.000000

The dataframe is large and has dates for the last 10 years (above is the head). I am trying to create a pivot table on date (for example summing all of the abs_nominal_trade_size values for each date. However I get a key error

KeyError: 'date'

When I try and pivot on the date using the following code:

 e = performanceData.pivot_table(index='date', columns=['abs_nominal_trade_size','abs_nominal_posn_size','nominal_posn_size'], values='Value')

Let's try:

performanceData.reset_index()\
               .pivot_table(index='date', 
                            values=['abs_nominal_trade_size',
                                     'abs_nominal_posn_size',
                                     'nominal_posn_size'],
                             aggfunc='sum')

Output:

            abs_nominal_posn_size  abs_nominal_trade_size  nominal_posn_size
date                                                                        
2016-01-04           143855.75251           604570.924714      120199.191686

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