用numpy中的变量[m]数组切片[m,n]数组

时间:2019-09-12 22:04:07

标签: python numpy slice

2 个答案:

答案 0 :(得分:1)

这是使用broadcasting的解决方案。


(a[:, None] <= np.arange(N)).view('i1')
# np.less_equal.outer(a, np.arange(N)).view('i1')

array([[0, 1, 1, 1, 1],
       [0, 1, 1, 1, 1],
       [0, 0, 1, 1, 1],
       [0, 0, 0, 0, 1],
       [1, 1, 1, 1, 1],
       [0, 1, 1, 1, 1],
       [0, 1, 1, 1, 1],
       [0, 0, 0, 1, 1]], dtype=int8)

答案 1 :(得分:0)

我不确定是否可以进行这样的切片。我建议您改为创建索引,然后对它们进行操作:

M = 8 
N = 5 
#a = np.random.randint(0, N, [M])  
a = np.array([1, 1, 2, 4, 0, 1, 1, 3])

from0toN = np.expand_dims(np.arange(N),0) # [[0,1,2,3,4]]

m = np.repeat(from0toN, M, axis=0)
#array([[0, 1, 2, 3, 4],
#             ...,
#       [0, 1, 2, 3, 4]])

boolean = m >= np.expand_dims(a,1)

onesAndZeroes = boolean.astype(int)

"""
array([[0, 1, 1, 1, 1],
       [0, 1, 1, 1, 1],
       [0, 0, 1, 1, 1],
       [0, 0, 0, 0, 1],
       [1, 1, 1, 1, 1],
       [0, 1, 1, 1, 1],
       [0, 1, 1, 1, 1],
       [0, 0, 0, 1, 1]])
"""