python - 从时间序列中提取 Pandas 中的每月分类(虚拟)变量

标签 python pandas

所以我有一个数据框(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/

相关文章:

python - 在 Pandas.read_excel 中使用转换器时可以使用列索引吗

python - 尝试将Excel文件中的数据导入RDS MySQL表中,插入时间太长

Python 如何保存 HTTP cookie

python 和 pandas - 如何使用 iterrows 访问列

Python Pandas 库按截断日期重新采样

python - 如何在 pandas DataFrame 中添加*或*更新列?

Python Pandas 数据框 : Find last occurrence of value less-than-or-equal-to current row

python - numpy package .npz 组件文件

python - 绘制 TreeViewItem 展开按钮和兄弟/子线

python - 对于维度 1 的数组,轴 1 超出范围