【发布时间】:2018-03-27 19:49:07
【问题描述】:
我希望在两对 numpy 数组之间随机播放,例如给定
a = [a1,a2,a3,a4]
a_next = [a2,a3,a4,a5]
b = [b1,b2,b3,b4]
b_next [b2,b3,b4,b5]
我想在 a 和 b 之间洗牌得到
x = [a1,b2,b3,a4]
x_next = [a2,b3,b4,a5]
y = [b1,a2,a3,b4]
y_next = [b2,a3,a4,b5]
我已经设法让这适用于一维 a 和 b,使用:
a = np.array([11,22,33,44])
a_next = np.array([22,33,44,55])
b = np.array([10,20,30,40])
b_next = np.array([20,30,40,50])
choices = [a,b]
choices_next = [a_next,b_next]
alternating_indices = np.random.randint(0, 2, len(a)) # Random 0s or 1s
x = np.choose(alternating_indices, choices)
x_next = np.choose(alternating_indices, choices_next)
y = np.choose(1-alternating_indices, choices)
y_next = np.choose(1-alternating_indices, choices_next)
但我真正的 a 和 b 实际上是 3D 数组(所以 a1、a2、...、b1、b2 的形状为 [width, height]),这会产生错误 ValueError: shape mismatch: objects cannot be broadcast to a single shape。这是一个给出相同错误的玩具示例:
a = np.array([[11,11],[22,22],[33,33],[44,44]])
a_next = np.array([[22,22],[33,33],[44,44],[55,55]])
b = np.array([[10,10],[20,20],[30,30],[40,40]])
b_next = np.array([[20,20],[30,30],[40,40],[50,50]])
那么,我怎样才能使它适用于具有非平凡形状元素的数组?实数数组 a、a_next、b 和 b_next 的形状相同 [M, width, height]。
提前致谢!
【问题讨论】:
-
我想过,但是使用布尔数组我可以在“a or nothing”和“b or nothing”之间进行选择,但我想选择“a or b”。有没有办法使用布尔数组来做到这一点?
-
你是对的!我也没有考虑过在作业左侧使用布尔索引。谢谢!