Pandas数据框索引按年份计算

时间:2015-09-19 10:46:39

标签: python pandas indexing

我制作了一堆像这样组织的数据帧(让我们调用这个df):

                   2014-12-31   2013-12-31  2012-12-31  2011-12-31
After Tax ROE     32             11          318        114
Cash Ratio        91             126          41        159
Current Ratio     152            188          97        195
Gross Margin      28             23           7         30
Operating Margin  6              3            95        123
Pre-Tax Margin    9              4            96        124
Pre-Tax ROE       31             11           318       113
Profit Margin     9              4            96        125
Quick Ratio       107            137          48        169

我写了一个脚本来刮刮纳斯达克网站,并为不同的股票制作了一堆这些。我希望能够以这种格式比较不同股票的一年的这些比率:

2014
      AAPL GOOG TSLA 

ratio  int  int  int
ratio  int  int  int
ratio  int  int  int
ratio  int  int  int

我知道我可以像这样df[[0]]引用列来获取该特定数据帧的2014年列。

但是我想根据年份进行索引,因此无论列的方向如何,它总是有效。我专门为此目的制作了df datetime对象的列标题。我该怎么做?

1 个答案:

答案 0 :(得分:0)

您可以将列设为DateTimeIndex,选择更灵活。

例如:

import pandas as pd
import numpy as np

df = pd.DataFrame(
    np.arange(10).reshape((5, 2)),
    columns=pd.DatetimeIndex(['2014-04-14', '2015-05-15']))
print(df['2014'])