python - 将数组切成段

标签 python numpy numpy-ndarray array-broadcasting numpy-slicing

假设我有一个数组[1,2,3,4,5,6,7,8],该数组由两个样本组成[1,2,3 ,4][5,6,7,8]。对于每个样本,我想要做一个窗口大小为 n 的切片窗口。如果元素不够,则用最后一个元素填充结果。返回值中的每一行应该是从该行中的元素开始的切片窗口。

例如: 如果n=3,那么结果应该是:

[[1,2,3],
 [2,3,4],
 [3,4,4],
 [4,4,4],
 [5,6,7],
 [6,7,8],
 [7,8,8],
 [8,8,8]]

如何通过高效切片而不是 for 循环来实现此目的?谢谢。

最佳答案

使用一些 numpy 内置功能的 @hpaulj 的类似方法

import numpy as np


samples = [[1,2,3,4],[5,6,7,8]]
ws = 3 #window size

# add padding
samples = [s + [s[-1]]*(ws-1) for s in samples]

# rolling window function for arrays
def rolling_window(a, window):
    shape = a.shape[:-1] + (a.shape[-1]-window+1, window)
    strides = a.strides + (a.strides[-1],)
    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)


result = sum([rolling_window(np.array(s), ws).tolist() for s in samples ], [])

result
[[1, 2, 3],
 [2, 3, 4],
 [3, 4, 4],
 [4, 4, 4],
 [5, 6, 7],
 [6, 7, 8],
 [7, 8, 8],
 [8, 8, 8]]

关于python - 将数组切成段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59796453/

相关文章:

python - 类型错误 : Argument 2 must support iteration (even though it does? )

python - 处理图像时如何标准化 scipy 的 convolve2d?

python - 将 numpy.array 存储在 Pandas.DataFrame 的单元格中

python - NumPy 数组的滚动/增加维数

python - 如何在没有换行符的情况下打印numpy对象

python - 在 Python 中为字典中的值制作字典

python - Flask URL 路由 : Route All other URLs to some function

python - 在 pandas 中是否有类似 GroupBy.get_group 的东西,但有一个可选的默认值?

python - 使用 iperf3 和 tcpdump 计算发送和接收数据包之间的时间延迟?

python - 如何仅更改 numpy 数组字典中的一个值