Divide DataFrame by first row

前端 未结 2 779
生来不讨喜
生来不讨喜 2021-02-05 21:22

I have checked the documentation. I don\'t understand the way to index a Pandas DataFrame.

I would like to divide a DataFrame of stock prices by their respective initial

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-05 22:16

    For new version of Pandas

    In [1]: df
    Out[1]:
                       SPY      Google        Gold        Xom
    Date
    2008-12-31   90.239998  153.250580   86.519997  79.830002
    2009-01-02   92.959999  160.060059   86.230003  81.639999
    2009-01-05   92.849998  163.412491   84.480003  81.629997
    2009-01-06   93.470001  166.406265   85.129997  80.300003
    2009-01-07   90.669998  160.403763   82.750000  78.250000
    ...                ...         ...         ...        ...
    2012-12-24  142.350006  353.425262  160.619995  86.919998
    2012-12-26  141.750000  353.111450  160.779999  87.070000
    2012-12-27  141.559998  351.826263  161.160004  86.860001
    2012-12-28  140.029999  348.697998  160.539993  85.099998
    2012-12-31  142.410004  352.369232  162.020004  86.550003
    
    [1007 rows x 4 columns]
    
    In [2]: df.iloc[0]
    Out[2]:
    SPY        90.239998
    Google    153.250580
    Gold       86.519997
    Xom        79.830002
    Name: 2008-12-31 00:00:00, dtype: float64
    
    In [3]: df.div(df.iloc[0])
    Out[3]:
                     SPY    Google      Gold       Xom
    Date
    2008-12-31  1.000000  1.000000  1.000000  1.000000
    2009-01-02  1.030142  1.044434  0.996648  1.022673
    2009-01-05  1.028923  1.066309  0.976422  1.022548
    2009-01-06  1.035793  1.085844  0.983934  1.005888
    2009-01-07  1.004765  1.046676  0.956426  0.980208
    ...              ...       ...       ...       ...
    2012-12-24  1.577460  2.306192  1.856449  1.088814
    2012-12-26  1.570811  2.304144  1.858299  1.090693
    2012-12-27  1.568706  2.295758  1.862691  1.088062
    2012-12-28  1.551751  2.275345  1.855525  1.066015
    2012-12-31  1.578125  2.299301  1.872631  1.084179
    
    [1007 rows x 4 columns]
    

提交回复
热议问题