python - 创建数据索引位置的滑动窗口
问题描述
我正在尝试编写一个函数,该函数将 Pandas DataFrame 上的滑动窗口的索引位置作为 (train, test) 元组的列表返回。
例子:
df.head(10)
col_a col_b
0 20.1 6.0
1 19.1 7.1
2 19.1 8.9
3 16.5 11.0
4 16.0 11.1
5 17.4 8.7
6 19.3 9.7
7 22.8 12.6
8 21.4 11.9
9 23.0 12.8
def split_function(df, train_length, test_length):
some_logic_to_split_dataframe
split_indices = [(train_idx, test_idx) for index_tuples in split_dataframe_logic]
return split_indices
期望的结果:
train_length = 2
test_length = 1
split_indices = split_function(df, train_length, test_length)
split_indices
output:
[((0,1), (2)), ((1,2),(3)),...,((7,8), (9)) etc]
当 test_index == 最后一次观察时,函数循环/生成器表达式也需要终止。
非常感谢所有帮助
解决方案
我建议使用rolling
提供的方法pandas
。
split_indices = []
def split(x):
split_indices.append((x.index[:train_length], x.index[-test_length:]))
return np.nan
df['col1'].rolling(train_length + test_length).apply(split)
此代码将创建以下内容split_indices
>>> split_indices
[(Int64Index([0, 1], dtype='int64'), Int64Index([2], dtype='int64')),
(Int64Index([1, 2], dtype='int64'), Int64Index([3], dtype='int64')),
(Int64Index([2, 3], dtype='int64'), Int64Index([4], dtype='int64')),
(Int64Index([3, 4], dtype='int64'), Int64Index([5], dtype='int64')),
(Int64Index([4, 5], dtype='int64'), Int64Index([6], dtype='int64')),
(Int64Index([5, 6], dtype='int64'), Int64Index([7], dtype='int64')),
(Int64Index([6, 7], dtype='int64'), Int64Index([8], dtype='int64')),
(Int64Index([7, 8], dtype='int64'), Int64Index([9], dtype='int64'))]
在您可以轻松获取给定索引的数据框的数据之后
>>> df.loc[split_indices[3][0]]
col1 col2
3 16.5 11.0
4 16.0 11.1
推荐阅读
- office-js - ScriptLab 数据透视表示例不再起作用
- jquery - 基于类别选择栏呈现字段
- vue.js - Vuetify 日期选择器 - 如何设置对话框使用的初始日期
- python - 在 OSmnx 中将街道划分为更小的部分
- firebase - Firebase 存储安全规则 - 对象的属性大小未定义
- python - 如果我调用starmap 两次或更多次会有问题吗?
- laravel - Laravel 迁移遇到问题
- javascript - 将 JSON 数据从 JavaScript 发送到 Servlet
- python - python比较两个excel文件并删除重复数据
- c# - 为什么一个扩展发生变异,而另一个没有