按时间索引时将 pandas 数据帧拆分为训练集和测试集
splitting pandas dataframe into training and test sets when indexed by time
如果我有一个按时间索引的数据框,如何将它分成训练集和测试集 2/3 训练和 1/3 测试?
我是否必须创建一个新的连续增加的整数列,然后对新的整数列使用 set_index()?
或者我可以在保持时间索引的同时这样做吗?如果是这样,我不知道该怎么做。
我必须手动选择一个日期作为分割点还是有其他方法?
只需使用 iloc
这是一种基于整数的索引方法,索引是时间数据类型这一事实在使用 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
这里的警告可以忽略,使用floor是因为3.3333不是有效的索引值
您还可以使用 scikit-learns cross-validation 方法,该方法将为您 return 训练测试拆分索引。
如果我有一个按时间索引的数据框,如何将它分成训练集和测试集 2/3 训练和 1/3 测试?
我是否必须创建一个新的连续增加的整数列,然后对新的整数列使用 set_index()?
或者我可以在保持时间索引的同时这样做吗?如果是这样,我不知道该怎么做。
我必须手动选择一个日期作为分割点还是有其他方法?
只需使用 iloc
这是一种基于整数的索引方法,索引是时间数据类型这一事实在使用 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
这里的警告可以忽略,使用floor是因为3.3333不是有效的索引值
您还可以使用 scikit-learns cross-validation 方法,该方法将为您 return 训练测试拆分索引。