根据一维计数器数组填充二维数组列
Filling of 2D array columns according to 1D counter array
我正在寻找一个 numpy 解决方案来填充二维数组中的每一列(下例中的 "a"),其中包含在不同的一维计数器数组中定义的多个“1”值("cnt" 在下面的例子中)。
我试过以下方法:
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.]])
我正在寻找一个 numpy 解决方案来填充二维数组中的每一列(下例中的 "a"),其中包含在不同的一维计数器数组中定义的多个“1”值("cnt" 在下面的例子中)。
我试过以下方法:
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.]])