Divide DataFrame by first row

Viewed 13276

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 values to index the different stocks to 100. I want to compare their performance. The DataFrame looks like this:

>>> IndexPrices
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 157 entries, 1999-12-31 00:00:00 to 2012-12-31 00:00:00
Freq: M
Data columns:
MSCI WORLD :G U$                        148  non-null values
S&P 500 COMPOSITE                       148  non-null values
DAX 30 PERFORMANCE                      148  non-null values
RUSSELL 2000                            148  non-null values
FTSE 100                                148  non-null values
US Treasury Bond Yields 30 Year Bond    148  non-null values
dtypes: float64(6)

I have stuff like this, but it's not getting me anywhere.

IndexPrices.divide(IndexPrices[0:1])
3 Answers

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]

To find the normalization of stock prices based on their initial values:

first_row = prices.iloc[0]
norm = prices.divide(first_row, axis=1)

The .iloc property is used to select the first row by index and axis=1 ensures that the each row scalar is used to divide stock prices in the correct column.

Related