通过循环中的索引数组对 numpy 数组进行索引

问题描述 投票:0回答:1

我有一个向量,我想批量洗牌。
我想出的想法是将其重塑为二维数组,每行作为一个批次。
然后我自己洗牌每一行。

这是该方法的玩具示例

# shuffle the matrix
mat_size = (8, 8)
row_size = 4

# generate the row and column indices
# shuffle the column
col_idx = np.arange(mat_size[0] * mat_size[1], dtype = np.int32) 

tmp_mat = np.reshape(col_idx, (-1, row_size))

for row in tmp_mat:
  idx = np.random.choice(row_size, size = row_size, replace = False)
  row[idx] = row # in place on col_idx

tmp_mat

我得到的结果:

array([[ 1,  0,  0,  0],
       [ 4,  5,  6,  4],
       [ 8,  9,  9,  8],
       [12, 12, 14, 12],
       [16, 17, 17, 19],
       [21, 20, 20, 21],
       [25, 26, 24, 24],
       [28, 29, 28, 31],
       [33, 34, 32, 32],
       [36, 36, 38, 38],
       [40, 41, 41, 43],
       [44, 44, 46, 46],
       [48, 48, 50, 48],
       [53, 52, 53, 52],
       [56, 57, 56, 57],
       [61, 60, 62, 60]])

问题在于这些行不是输入行的打乱版本。
可以看作原始数组每行都有唯一的值。 我不确定这里会发生什么。

我确实发现,如果我用

row[idx] = row
替换
row[:] = row[idx]
,它就可以工作。

对发生的事情有解释吗?
为什么作业没有按我的预期进行?

python arrays numpy for-loop variable-assignment
1个回答
0
投票

您的问题是由于在引用该行时尝试修改该行所致。

如果您使用副本,就不会有问题:

row[idx] = row.copy()

也不是,正如您通过这样做发现的:

row[:] = row[idx]

这也是使用副本

© www.soinside.com 2019 - 2024. All rights reserved.