[英]Numpy assign an array value based on the values of another array with column selected based on a vector
我有一個二維數組
X
array([[2, 3, 3, 3],
[3, 2, 1, 3],
[2, 3, 1, 2],
[2, 2, 3, 1]])
和一維數組
y
array([1, 0, 0, 1])
對於X的每一行,我想找到X值為最低且y值為1的列索引,並將第三矩陣中的對應行列對設置為1
例如,在X的第一行的情況下,對應於最小X值(僅對於第一行)且y = 1的列索引為0,那么我希望Z [0,0] = 1且所有其他Z [0,i] =0。類似地,對於第二行,列索引0或3給出y = 1的最低X值。然后我希望Z [1,0]或Z [1,3] = 1(最好Z [1,0] = 1,所有其他Z [1,i] = 0,因為首先出現0列)
我最后的Z數組看起來像
Z
array([[1, 0, 0, 0],
[1, 0, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 1]])
一種方法是使用掩碼數組。
import numpy as np
X = np.array([[2, 3, 3, 3],
[3, 2, 1, 3],
[2, 3, 1, 2],
[2, 2, 3, 1]])
y = np.array([1, 0, 0, 1])
#get a mask in the shape of X. (True for places to ignore.)
y_mask = np.vstack([y == 0] * len(X))
X_masked = np.ma.masked_array(X, y_mask)
out = np.zeros_like(X)
mins = np.argmin(X_masked, axis=0)
#Output: array([0, 0, 0, 3], dtype=int64)
#Now just set the indexes to 1 on the minimum for each axis.
out[np.arange(len(out)), mins] = 1
print(out)
[[1 0 0 0]
[1 0 0 0]
[1 0 0 0]
[0 0 0 1]]
您可以使用numpy.argmin()
獲得X
每一行的最小值的索引。 例如:
import numpy as np
a = np.arange(6).reshape(2,3) + 10
ids = np.argmin(a, axis=1)
同樣,您可以通過numpy.nonzero
或numpy.where
來索引y為1的索引。 一旦有了兩個索引數組,就可以輕松設置第三個數組中的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.