我有一个A
形状为(N,)的数组。我以N = 5为例:
A = np.array([0,1,1,0,1])
我想将其转换为以下NxN矩阵B
。NumPy和Tensorflow中的解决方案都不错,但后者是首选。
B = np.array([[0,1,1,0,1],
[0,1,1,0,1],
[0,1,1,0,1],
[0,0,0,0,1],
[0,0,0,0,1]])
一种解决方案可以包括以下步骤:
A
N次i
。查找最后i-th
一行零的索引,直到该行的元素为止。N = 10的另一个例子:
D = np.array([0,1,1,1,0,0,1,1,0,0])
E = np.array([[0,1,1,1,0,0,1,1,0,0],
[0,1,1,1,0,0,1,1,0,0],
[0,1,1,1,0,0,1,1,0,0],
[0,1,1,1,0,0,1,1,0,0],
[0,0,0,0,0,0,1,1,0,0],
[0,0,0,0,0,0,1,1,0,0],
[0,0,0,0,0,0,1,1,0,0],
[0,0,0,0,0,0,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0]])
A = np.array([0,1,1,0,1])
N = A.shape[0]
column = (A > 0).reshape((N, 1))
mask = np.ones((N, N), dtype=np.bool)
mask = np.where(column, False, np.tril(mask, -1))
mask = np.cumsum(mask, axis=0)
B = np.where(mask, 0, np.tile(A, (N, 1)))
[[0 1 1 0 1]
[0 1 1 0 1]
[0 1 1 0 1]
[0 0 0 0 1]
[0 0 0 0 1]]
[[False False False False False]
[ True False False False False]
[ True True False False False]
[ True True True False False]
[ True True True True False]]
[[False False False False False]
[False False False False False]
[False False False False False]
[ True True True False False]
[False False False False False]]
[[0 0 0 0 0]
[0 0 0 0 0]
[0 0 0 0 0]
[1 1 1 0 0]
[1 1 1 0 0]]
[[0 1 1 0 1]
[0 1 1 0 1]
[0 1 1 0 1]
[0 1 1 0 1]
[0 1 1 0 1]]
[[0 1 1 0 1]
[0 1 1 0 1]
[0 1 1 0 1]
[0 0 0 0 1]
[0 0 0 0 1]]