我查过了文档。我不明白索引Pandas DataFrame的方法。
我想将股票价格的DataFrame除以各自的初始值,将不同的股票指数编制为100.我想比较他们的表现。 DataFrame看起来像这样:
>>> 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)
我有这样的东西,但它并没有把我带到任何地方。
IndexPrices.divide(IndexPrices[0:1])
答案 0 :(得分:16)
In [193]: df
Out[193]:
A B C D
a 1 8 9 1
b 5 4 3 6
c 4 6 1 3
d 1 0 2 9
In [194]: df.divide(df.ix[0] / 100)
Out[194]:
A B C D
a 100 100 100.000000 100
b 500 50 33.333333 600
c 400 75 11.111111 300
d 100 0 22.222222 900
答案 1 :(得分:1)
对于新版本的熊猫
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]