在行[NumberPy或Tensorflow]的索引值之前,将行中的值设置为零



我有一个形状为(N,(的数组A。我用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]])

一个解决方案可以包括以下步骤:

  1. 重复数组AN次
  2. 循环通过每一行i。查找最后一个零的索引,直到该行的i-th元素为止
  3. 将该索引之前的所有元素替换为零

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]]

解释

  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]]
  1. 在A中查找,并用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]]
  1. 计算累积和,为下面的所有行设置零。这是所有应该归零的元素的掩码
[[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]]
  1. 重复数组A N次
[[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]]
  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]]

@rafiko1我仍然不清楚你的解释。但请尝试以下内容。

import numpy as np
nn = 5
A = np.array([0,1,1,0,1])
#A = np.array([0,1,1,1,0,0,1,1,0,0])
#  we create the matrix B and set required entries to zero
B = np.repeat(A.reshape(1,nn),nn,axis=0)
# test condition:
# test if the ith element in the ith row is zero
# this is accomplished using np.diag
boolarr = np.diag(B==0)
# this gives us the row index in B where the condition is true
idx_b_rows = np.where(boolarr == True)
# get indices of entries before diagonal
idx_lower_rows,idx_lower_cols = np.tril_indices(nn,k=-1)
# get the indices of the entries of idx_b_rows in idx_lower_rows
idx = np.where(np.in1d(idx_lower_rows,idx_b_rows))[0]
# set the entries before the diagonal to zero
B[idx_lower_rows[idx],idx_lower_cols[idx]] = 0
print(B)

最新更新