![](/img/trans.png)
[英]How to assign ones and zeros to specific indices of an array using numpy?
[英]Padding a numpy array with zeros, and using another array as an index for ones
我正在嘗試填充一個numpy
數組,但似乎無法從numpy的文檔中找到正確的方法。 我有一個數組:
a = array([2, 1, 3, 5, 7])
這代表我要創建的數組的索引。 因此,在索引值為2或1或3等的情況下,我想在數組中以及目標數組中的其他所有地方都添加一個零。 有點像數組掩碼。 我還想指定目標數組l
的總長度。 所以我理想的功能是這樣的:
>>> foo(a,l)
array([0,1,1,1,0,1,0,1,0,0,0]
,對於上面的示例,其中l=10
。
編輯:
所以我寫了這個函數:
def padwithones(a,l) :
p = np.zeros(l)
for i in a :
p = np.insert(p,i,1)
return p
這使:
Out[19]:
array([ 0., 1., 0., 1., 1., 1., 0., 1., 0., 0., 0., 0., 0.,
0., 0.])
哪個不正確!
您正在尋找的基本上是一個熱點陣列:
def onehot(foo, l):
a = np.zeros(l, dtype=np.int32)
a[foo] = 1
return a
例:
In [126]: onehot([2, 1, 3, 5, 7], 10)
Out[126]: array([0, 1, 1, 1, 0, 1, 0, 1, 0, 0])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.