從兩個 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)
uj5u.com熱心網友回復:
嘗試添加一個新維度:
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]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/341059.html
