自定义NumPy切片

时间:2019-01-02 13:31:36

标签: python numpy numpy-slicing

我有一堆形状可能不同的numpy数组:

[[1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1]]

我需要选择索引并将其存储到变量中,以便可以将数组更改为:

[[1, 1, 1, 1, 1],
 [1, 1, 1, 1, 0],
 [1, 1, 1, 1, 0],
 [0, 0, 0, 0, 0]]

我可以获取垂直索引:

idx = np.s_[1:4, 3]

但是我不知道如何从最后一行添加所有索引并将其存储到idx

更新

我想要索引。有时我需要引用这些索引中的值,并且有时候我想更改那些索引中的值。拥有索引将使我能够灵活地同时执行这两项操作。

2 个答案:

答案 0 :(得分:0)

这不是像以前那样使用切片,但是numpy允许您使用列表建立索引,以便可以存储所有要更改的坐标。

A = np.ones((4,5))

col = np.zeros(7,dtype='int')
row = np.zeros(7,dtype='int')

col[:5] = np.arange(5)
col[5:] = 4

row[:5] = 3
row[5:] = np.arange(1,3)

A[row,col] = 0

您还可以使用两个切片idx1 = np.s_[1:4,3]idx2 = np.s_[3,0:5]并同时应用它们。

答案 1 :(得分:0)

我不知道内置的NumPy方法,但是也许可以做到:

import numpy as np

a = np.random.rand(16).reshape((4, 4))   # Test matrix (4x4)
inds_a = np.arange(16).reshape((4, 4))   # Indices of a
idx = np.s_[0:3, 3]     # Vertical indices
idy = np.s_[3, 0:3]     # Horizontal indices

# Construct slice matrix
bools = np.zeros_like(a, dtype=bool)
bools[idx] = True
bools[idy] = True

print(a[bools])         # Select slice from matrix
print(inds_a[bools])    # Indices of sliced elements