python - Numpy 切片函数 : Dynamically create slice indices np. r_[a :b, c :d, ...] 来自形状为 (X, 2) 的数组,用于在数组中进行选择

标签 python arrays python-3.x numpy slice

情况

我有代表双 channel 音频的二维数组。我想创建一个函数,在任意位置返回该数组的切片(例如仅语音部分)。当我将值显式写入 np.r_ 时,我已经知道如何执行此操作:

示例数据

arr = np.arange(0,24).reshape((2, -1))
# array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11],
#        [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]])

输入

宽度为 2 的 x 长度数组。例如

selector = np.array([[0, 2], [6, 9]])
# array([[0, 2],
#        [6, 9]])

期望的输出

# create an indexed arrays
selection_indices = np.r_[0:2, 6:9]
# array([0, 1, 6, 7, 8])

# use indices to select 2D
arr[:, selection_indices]
# array([[ 0,  1,  6,  7,  8],
#        [12, 13, 18, 19, 20]])

目标

一个函数,它采用宽度为 2 的 X 长度数组(形状:X, 2),表示切片的开始和结束,并使用它返回数组的选择。实际上是np.r_[0:2, 6:9],但是来自一个参数。

arr = np.arange(0,24).reshape((2, -1))

def slice_returner(arr, selector):
    # something like this (broken); should be like: np.r_[0:2, 6:9]
    selection_indices = np.r_[[row[0]:row[1]] for row in selector]
    # return 2D slice
    return arr[:, selection_indices]

selector = np.array([[0, 2], [6, 9]])
sliced_arr = slice_returner(arr, selector)

如何将输入转换为选择切片?最好具有最少的数组创建/复制。

最佳答案

认为 bool 索引可能是一种有效的方法。因此,我们可以创建一个掩码,然后索引 cols 并获得我们的输出 -

# Generate mask for cols
mask = np.zeros(arr.shape[1],dtype=bool)
for (i,j) in selector:
    mask[i:j] = True

# Boolean index into cols for final o/p
out = arr[:,mask]

内存开销只是掩码,作为 bool 数组应该是最小的,并且最终输出是必需的。

矢量化蒙版创建

如果选择器中有很多条目,则有一种基于广播的矢量化方法来为列创建掩码,如下所示 -

r = np.arange(arr.shape[1])
mask = ((selector[:,0,None]<=r) & (selector[:,1,None]>r)).any(0)

关于python - Numpy 切片函数 : Dynamically create slice indices np. r_[a :b, c :d, ...] 来自形状为 (X, 2) 的数组,用于在数组中进行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58991395/

相关文章:

python - 在仍然理智的情况下在 Django 中设置通用外键

python - 从 Python 中的函数获取类引用

python - 如何在UpdateView(Django)中获取模型实例的属性?

python - 需要帮助在 python3 中解析 html,对于 xml.etree.ElementTree 来说格式不够好

Python字符生成

PHP从KML文件获取坐标

Javascript 数组到 php 的 post

c - 为什么在 C 中不能将二维数组转换为二维指针?

python - 身份验证失败,代码为 32

python - 在 TF 估计器中使用 Keras 模型