[英]Filling of 2D array columns according to 1D counter array
我正在尋找一種numpy解決方案,以在二維數組(在下面的示例中為“ a”)中的每一列填充不同的一維計數器數組(在以下示例中為“ cnt”)中定義的多個“ 1”值。
我嘗試了以下方法:
import numpy as np
cnt = np.array([1, 3, 2, 4]) # cnt array: how much elements per column are 1
a = np.zeros((5, 4)) # array that must be filled with 1s per column
for i in range(4): # for each column
a[:cnt[i], i] = 1 # all elements from top to cnt value are filled
print(a)
並給出所需的輸出:
[[1. 1. 1. 1.]
[0. 1. 1. 1.]
[0. 1. 0. 1.]
[0. 0. 0. 1.]
[0. 0. 0. 0.]]
是否有一個更簡單(更快)的numpy例程來做到這一點,而不必每列都有循環?
a = np.full((5, 4), 1, cnt)
像上面的東西會很好,但是不起作用。
感謝您的時間!
您可以使用np.where
進行廣播,如下所示:
>>> import numpy as np
>>>
>>> cnt = np.array([1, 3, 2, 4]) # cnt array: how much elements per column are 1
>>> a = np.zeros((5, 4)) # array that must be filled with 1s per column
>>>
>>> res = np.where(np.arange(a.shape[0])[:, None] < cnt, 1, a)
>>> res
array([[1., 1., 1., 1.],
[0., 1., 1., 1.],
[0., 1., 0., 1.],
[0., 0., 0., 1.],
[0., 0., 0., 0.]])
或就地:
>>> a[np.arange(a.shape[0])[:, None] < cnt] = 1
>>> a
array([[1., 1., 1., 1.],
[0., 1., 1., 1.],
[0., 1., 0., 1.],
[0., 0., 0., 1.],
[0., 0., 0., 0.]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.