从两个 NumPy 数组中随机选取行

Picking rows from two NumPy arrays at random

从两个 numpy 数组开始:

A = np.array([[1, 2], [2, 3], [3, 4], [4, 5]])
B = np.array([[9, 8], [8, 7], [7, 6], [6, 5]])

我想创建一个新数组 C 为每个索引从同一索引中随机选择一行,但从 AB 中随机选择。这个想法是,在 random_selector 的每个索引处,如果值高于 0.1,那么我们从 A 中选择相同索引的行,否则,从 B.

random_selector = np.random.random(size=len(A))

C = np.where(random_selector > .1, A, B)

# example of desired result picking rows from respectively A, B, B, A:
# [[1, 2], [8, 7], [7, 6], [4, 5]]

运行 但是,上面的代码会产生以下错误:

ValueError: operands could not be broadcast together with shapes (4,) (4,2) (4,2) 

尝试添加新维度:

import numpy as np

A = np.array([[1, 2], [2, 3], [3, 4], [4, 5]])
B = np.array([[9, 8], [8, 7], [7, 6], [6, 5]])

random_selector = np.random.random(size=len(A))

C = np.where((random_selector > .1)[:, None], A, B)
print(C)

输出(单个运行)

[[1 2]
 [8 7]
 [3 4]
 [4 5]]