【发布时间】:2021-12-14 02:51:42
【问题描述】:
从两个numpy数组开始:
A = np.array([[1, 2], [2, 3], [3, 4], [4, 5]])
B = np.array([[9, 8], [8, 7], [7, 6], [6, 5]])
我想创建一个新数组C,为每个索引从同一索引中选择一行,但从A 或B 中随机选择。思路是在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)
【问题讨论】:
标签: python numpy multidimensional-array random