从给定起始索引的一维数组中提取子数组-Python / NumPy [英] Extract subarrays from 1D array given start indices - Python / NumPy

查看:97
本文介绍了从给定起始索引的一维数组中提取子数组-Python / NumPy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

NumPy数组可以与其他数组建立索引。为了说明:

NumPy arrays may be indexed with other arrays. To illustrate:

>>> import numpy as np

>>> arr = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0et ], 'f4')
>>> ids = np.array([0, 2], 'i4')
arr[ids]
array([ 0.,  2.], dtype=float32)

但是,如果我想拥有一个包含索引所指向的值和三个后续元素的多数组,该怎么办?

But what if I wanted to have a multiarray with the value pointed by the index plus the three subsequents elements?

>>> arr[ids:(ids+4)]
Traceback (most recent call last):
  File "<console>", line 1, in <module>
IndexError: invalid slice

预期:

array([[0. 1. 2. 3.], [2. 3. 4. 5.]], dtype=float32)

如何做到这一点?

推荐答案

使用 广播的 创建所有这些索引,然后创建索引-

Use broadcasted addition to create all those indices and then index -

all_idx = ids[:,None]+range(4) # or np.add.outer(ids, range(4))
out = arr[all_idx]

使用 np.lib.stride_tricks.as_strided 基于 strided_app -

strided_app(arr, 4, S=1)[ids]

这篇关于从给定起始索引的一维数组中提取子数组-Python / NumPy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆