问题
Suppose
A = np.array([[1,2,0,3,5,0,0],[5,6,7,0,9,5,10]])
(The actual data set in this case is a square matrix with a shifted diagonal of zeros) I want to create an np array V that sums the pairs reflected across the first zero in each row, in the order of their distance from the zero. i.e., V[0]=[(2+3),(1+5),0] V[1] =[(7+9),(6+5),(10+5)]...
So
V = ([5,6,0],[16,11,15])
I can accomplish this in a very rudimentary way by looping through each row and then adding each row to a shifted version of its reflection, with just two rows it would be something simple like this.
B = A.copy()
B = B[...,::-1]
V = np.array([A[0]+np.roll(B[0],-2),A[1]+B[1]])[:,0:3]
However I'm wondering if there is a vectorized approach to this operation, or some function native to numpy that sums an entry of an array along with its reflection across its diagonal because as the data set gets large this becomes less efficient.
来源:https://stackoverflow.com/questions/64408577/is-there-a-way-to-sum-a-matrix-entry-and-its-reflection-across-a-diagonal-along