问题描述
我正在寻找与sum()
相反的东西.我们开始:
I'm looking for sort of the opposite of sum()
I guess. 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])
所以我想朝相反的方向:从[0,1,2,3]
到类似x
的数组(我可以在x中指定我想要的列数,当然要大于5).
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).
理想情况下,该解决方案也应该适用于更高的尺寸,并且我当然也不想在Python中循环,因为输入内容可能比此示例更长.也就是说,这是一个使用循环的解决方案:
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. 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-但我不确定我可以这样做-您可以使用arange
和广播比较:
IIUC -- and I'm not sure that I do -- you could use arange
and a broadcasting comparison:
>>> 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)
或二维:
>>> 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
这篇关于NumPy:创建布尔数组,例如"repeat".但在多个维度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!