我有兩個 numpy 陣列,一個帶有二維向量陣列,(z1_i,z2_i)另一個只是一維變數陣列c_i(這里的 i 表示陣列的索引)。我想對這兩個陣列進行操作,得到一個形式為一維變數的陣列z1_i*c_i z2_i*(1-c_i)(同樣,下標我指的是陣列的索引)。例如:
2D_samples= np.array([[1, 2], [3, 4]])
1D_samples = np.array([1, 0])
# desired output would be np.array([1, 4])
# Specifically, [1*1 2*(1-1), 3*0 4(1-0)]=[1,4].
有沒有更有效的方法可以在不執行 for 回圈的情況下執行此操作?謝謝。
通過 for 回圈執行此操作將給出:
output = np.zeros(2D_samples)
for i in range(len(2D_samples)):
output[i] = 2D_samples[i][0] * 1D_samples[i] 2D_samples[i][1] * (1 - c[i])
uj5u.com熱心網友回復:
IIUC,你可以這樣做:
a2D = np.array([[1, 2], [3, 4]])
a1D = np.array([1, 0])
# reshape the 1D array to 2D
b = a1D[:,None]
# concatenate b and 1-b column-wise, multiply by a2D and sum per row
out = (a2D * np.c_[b,1-b]).sum(1)
輸出:array([1, 4])
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/434075.html
上一篇:減去與熊貓中重復變數相關的值
