修改Pandas数据帧以列出年月和日期

时间:2015-03-24 02:57:17

标签: python pandas

我想修改我在下面创建的数据框:

from datetime import date
from dateutil.rrule import rrule, DAILY, YEARLY
from dateutil.relativedelta import *
import pandas

START_YR = 2010
END_YR = 2013

strt_date = datetime.date(START_YR, 1, 1)
end_date  = datetime.date(END_YR, 12, 31)

dt = rrule(DAILY, dtstart=strt_date, until=end_date)

serie_1 = pandas.Series(np.random.randn(dt.count()), \
        index = pandas.date_range(strt_date, end_date))

如何创建包含年份和日期的数据框作为单独的列?

2 个答案:

答案 0 :(得分:2)

将系列转换为DataFrame,然后将新列添加为Pandas时段。 如果您只想将月份作为整数,请参阅'month_int'示例。

df = pd.DataFrame(serie_1)
df['month'] = [ts.to_period('M') for ts in df.index]
df['year'] = [ts.to_period('Y') for ts in df.index]
df['month_int'] = [ts.month for ts in df.index]

>>> df
Out[16]: 
                   0   month   year  month_int

2010-01-01  0.332370  2010-01  2010          1
2010-01-02 -0.036814  2010-01  2010          1
2010-01-03  1.751511  2010-01  2010          1
...              ...      ...   ...        ...
2013-12-29  0.345707  2013-12  2013         12
2013-12-30 -0.395924  2013-12  2013         12
2013-12-31 -0.614565  2013-12  2013         12

答案 1 :(得分:2)

只需访问datetime属性即可快得多:

df['date'] = df.index.date
df['year'] = df.index.year
df['month'] = df.index.month

将时间与列表理解方法进行比较:

In [25]:

%%timeit
df['month'] = [ts.to_period('M') for ts in df.index]
df['year'] = [ts.to_period('Y') for ts in df.index]
df['month_int'] = [ts.month for ts in df.index]
1 loops, best of 3: 664 ms per loop
In [26]:

%%timeit
df['date'] = df.index.date
df['year'] = df.index.year
df['month'] = df.index.month

100 loops, best of 3: 5.96 ms per loop

因此,使用日期时间属性的速度要快100倍