python - numpy 如何使用数组对数组进行切片索引?

标签 python numpy

也许这已经在其他地方提出并解决了,但我还没有找到。
假设我们有一个 numpy 数组:

a = np.arange(100).reshape(10,10)
b = np.zeros(a.shape)
start = np.array([1,4,7])   # can be arbitrary but valid values
end = np.array([3,6,9])     # can be arbitrary but valid values
startend两者都有有效值,因此每个切片也对 a 有效.
我想复制 a 中子数组的值到 b 中的相应位置:
b[:, start:end] = a[:, start:end]   #error

此语法不起作用,但等效于:
b[:, start[0]:end[0]] = a[:, start[0]:end[0]]
b[:, start[1]:end[1]] = a[:, start[1]:end[1]]
b[:, start[2]:end[2]] = a[:, start[2]:end[2]]

我想知道是否有更好的方法来代替 start 上的显式 for 循环。和 end数组。

谢谢!

最佳答案

我们可以使用 broadcasting 使用与 start 的两组比较来创建要编辑的地点掩码和 end数组,然后简单地用 boolean-indexing 赋值对于矢量化解决方案 -

# Range array for the length of columns
r = np.arange(b.shape[1])

# Broadcasting magic to give us the mask of places
mask = (start[:,None] <= r) & (end[:,None] >= r)

# Boolean-index to select and assign 
b[:len(mask)][mask] = a[:len(mask)][mask]

sample 运行 -
In [222]: a = np.arange(50).reshape(5,10)
     ...: b = np.zeros(a.shape,dtype=int)
     ...: start = np.array([1,4,7])
     ...: end = np.array([5,6,9]) # different from sample for variety
     ...: 

# Mask of places to be edited
In [223]: mask = (start[:,None] <= r) & (end[:,None] >= r)

In [225]: print mask
[[False  True  True  True  True  True False False False False]
 [False False False False  True  True  True False False False]
 [False False False False False False False  True  True  True]]

In [226]: b[:len(mask)][mask] = a[:len(mask)][mask]

In [227]: a
Out[227]: 
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, 24, 25, 26, 27, 28, 29],
       [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
       [40, 41, 42, 43, 44, 45, 46, 47, 48, 49]])

In [228]: b
Out[228]: 
array([[ 0,  1,  2,  3,  4,  5,  0,  0,  0,  0],
       [ 0,  0,  0,  0, 14, 15, 16,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0, 27, 28, 29],
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0]])

关于python - numpy 如何使用数组对数组进行切片索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46734116/

相关文章:

python - 将一个数据框与另一个数据框分离

python - 更准确地搜索文本中的字符串

python - SQLite - 检查创建时的表格式并根据需要删除

python - numpy/pandas 向量化自定义 for 循环

python - 基于多标签掩码对 numpy 数组求和

python - Numpy Arrays : Slice y-values array based on threshold, 然后相应地对 x 值数组进行切片

python - Numpy 嵌套结构化数组引用

python - 如何调试 gunicorn 失败问题? ( worker 无法启动)

python - 部署 Flask,并行请求

python - 在python中创建3D矩阵的2D投影