所以我有一个数据框(df),其中包含每月时间序列(月底)的日期数据。它看起来像这样:
Date Data
2010-01-31 625000
2010-02-28 750000
...
2014-10-31 450000
2014-11-30 475000
我想检查季节性每月影响。
这可能很简单,但是我如何从 Date 中提取月份以创建用于回归的分类虚拟变量?
我希望它看起来像这样:
Date 01 02 03 04 05 06 07 08 09 10 11
2010-01-31 1 0 0 0 0 0 0 0 0 0 0
2010-02-28 0 1 0 0 0 0 0 0 0 0 0
...
2014-10-31 0 1 0 0 0 0 0 0 0 1 0
2014-11-30 0 1 0 0 0 0 0 0 0 0 1
我尝试使用 pd.DataFrame(df.index.month, index=df.index)... 这给了我每个日期的月份。我相信我需要使用 pandas.core.reshape.get_dummies 然后以 0/1 矩阵格式获取变量。有人可以告诉我怎么做吗?谢谢。
最佳答案
这就是我获得四月的方式:
import pandas as pd
import numpy as np
dates = pd.date_range('20130101', periods=4, freq='MS')
df = pd.DataFrame(np.random.randn(4), index=dates, columns=['data'])
df.ix[dates.month==4]
这个想法是将日期作为索引,然后在数据帧上进行 bool 索引选择。
>>> df
data
2013-01-01 0.141205
2013-02-01 0.115361
2013-03-01 -0.309521
2013-04-01 -0.236317
>>> df.ix[dates.month==4]
data
2013-04-01 -0.236317
关于python - 从时间序列中提取 Pandas 中的每月分类(虚拟)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27322561/