[英]NumPy: create bool array like “repeat” but in multiple dimensions
I'm looking for sort of the opposite of sum()
I guess. 我在寻找与sum()
相反的东西。 Here we go: 开始了:
x = array([
[False, False, False, False, False],
[ True, False, False, False, False],
[ True, True, False, False, False],
[ True, True, True, False, False]])
x.sum(axis=1)
Out: array([0, 1, 2, 3])
So I want to go the opposite direction: from [0,1,2,3]
to an array like x
(I can specify the number of columns I want in x, of course, above it's 5). 所以我想朝相反的方向:从[0,1,2,3]
到x
这样的数组(我可以在x中指定我想要的列数,当然要在5以上)。
The solution should ideally work for higher dimensions too, and I don't want to loop in Python of course, because the input could be longer than this example. 该解决方案在理想情况下也应该适用于更高的尺寸,并且我当然也不想在Python中循环,因为输入的时间可能比此示例长。 That said, here's a solution using a loop: 也就是说,这是一个使用循环的解决方案:
s = np.array([0, 1, 2, 3])
y = np.zeros((len(s), 5), np.bool)
for row,col in enumerate(s):
y[row,0:col] = True
IIUC -- and I'm not sure that I do -- you could use arange
and a broadcasting comparison: IIUC –我不确定我会这样做–您可以使用arange
和广播比较:
>>> v = np.array([0,1,3,2])
>>> np.arange(5) < v[...,None]
array([[False, False, False, False, False],
[ True, False, False, False, False],
[ True, True, True, False, False],
[ True, True, False, False, False]], dtype=bool)
or in 2D: 或二维:
>>> v = np.array([[1,2],[0,2]])
>>> np.arange(5) < v[...,None]
array([[[ True, False, False, False, False],
[ True, True, False, False, False]],
[[False, False, False, False, False],
[ True, True, False, False, False]]], dtype=bool)
>>> ((np.arange(5) < v[...,None]).sum(2) == v).all()
True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.