1

我有一堆形状不同的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

更新

我想要索引。有时我需要引用这些索引处的值,有时我想更改这些索引处的值。拥有索引将使我能够灵活地做到这两点。

4

2 回答 2

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]同时应用它们。

于 2019-01-02T13:54:30.847 回答
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
于 2019-01-02T14:01:02.377 回答