add a field in pandas dataframe with MultiIndex columns

后端 未结 4 718
长发绾君心
长发绾君心 2021-02-06 00:00

i have looked for an answer to this question as it seems pretty simple, but have not been able to find anything yet. Apologies if I missed something. I have pandas version 0.1

4条回答
  •  死守一世寂寞
    2021-02-06 00:11

    for this particular problem, it seems like using a Panel object works. I did the following (taking dftst from my original post):

    pn = dftst.T.to_panel()
    print pn
    
    Out[83]: 
    
    Dimensions: 12 (items) x 3 (major_axis) x 2 (minor_axis)
    Items axis: 2009-03-01 06:29:59 to 2009-03-12 06:29:59
    Major_axis axis: AAPL to GS
    Minor_axis axis: close to rate
    

    If I move the ('close', 'rate') to the Items by doing the following:

    pn = pn.transpose(2,0,1)
    print pn
    
    Out[91]: 
    
    Dimensions: 2 (items) x 12 (major_axis) x 3 (minor_axis)
    Items axis: close to rate
    Major_axis axis: 2009-03-01 06:29:59 to 2009-03-12 06:29:59
    Minor_axis axis: AAPL to GS
    

    Now I can do a time series operation and add it as a field in the Panel object:

    pn['avg_close'] = pandas.rolling_mean(pn['close'], 5)
    print pn
    
    Out[93]: 
    
    Dimensions: 3 (items) x 12 (major_axis) x 3 (minor_axis)
    Items axis: close to avg_close
    Major_axis axis: 2009-03-01 06:29:59 to 2009-03-12 06:29:59
    Minor_axis axis: AAPL to GS
    
    print pn['avg_close']
    
    Out[94]: 
    ticker                   AAPL      GOOG        GS
    2009-03-01 06:29:59       NaN       NaN       NaN
    2009-03-02 06:29:59       NaN       NaN       NaN
    2009-03-03 06:29:59       NaN       NaN       NaN
    2009-03-04 06:29:59       NaN       NaN       NaN
    2009-03-05 06:29:59  0.303719 -0.129300 -0.037954
    2009-03-06 06:29:59 -0.006839  0.206331  0.336467
    2009-03-07 06:29:59  0.128299  0.174935  0.698275
    2009-03-08 06:29:59  0.471010 -0.137343  0.671049
    2009-03-09 06:29:59 -0.279855 -0.033427  0.848610
    2009-03-10 06:29:59 -0.516032  0.260944  0.373046
    2009-03-11 06:29:59 -0.456213  0.164710  0.910448
    2009-03-12 06:29:59 -0.799156  0.544132  0.862764
    

    I am actually having some other problems with the Panel objects, but I will leave those to another post.

提交回复
热议问题