在按时间索引时将pandas数据帧拆分为训练和测试集

azu*_*ric 3 python pandas

如果我有一个按时间索引的数据帧怎么能把它分成训练和测试集2/3rds训练和1/3测试?

我是否必须创建一个连续增加整数的新列,然后使用set_index()到新的整数列?

或者我可以在保持时间指数的同时做到这一点吗?如果是这样,我不知道该怎么做.

我是否必须手动选择日期作为分割点,还是有其他方式?

EdC*_*ica 5

只使用iloc哪个是基于整数的索引方法,索引是时间dtype的事实在使用时无关紧要iloc:

In [6]:

df = pd.DataFrame({'a':['1','2','3','4','5']})
df.iloc[0: floor(2 * len(df)/3)]

C:\WinPython-64bit-3.3.5.0\python-3.3.5.amd64\lib\site-packages\pandas\core\index.py:687: FutureWarning: slice indexers when using iloc should be integers and not floating point
  "and not floating point",FutureWarning)
Out[6]:
   a
0  1
1  2
2  3
In [7]:

df.iloc[floor(2 * len(df) /3):]
Out[7]:
   a
3  4
4  5
Run Code Online (Sandbox Code Playgroud)

你可以忽略这里的警告,使用楼层是因为3.3333不是有效的索引值

您还可以使用scikit-learn 交叉验证方法,它将为您返回列车测试拆分索引.