首页 > 解决方案 > 创建数据索引位置的滑动窗口

问题描述

我正在尝试编写一个函数,该函数将 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 == 最后一次观察时,函数循环/生成器表达式也需要终止。

非常感谢所有帮助

标签: pythonpandasnumpy

解决方案


我建议使用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

推荐阅读