Shew
Shew

Reputation: 1596

subtract rows one by one from numpy array

I have a 2D numpy array, A.

I want to subtract each rows, one by one, from A, and store the row-wise absolute sum in an array.

Is there a way to carry out the operation without using the for loop ? Below is the code with for loop.

import numpy as np
A = np.random.randint(5,size=(8,9))
b = np.zeros(A.shape[1]);
for i in xrange(A.shape[0]):
    b = b + np.sum(np.absolute(A - A[i,:]), axis=0)

Upvotes: 1

Views: 237

Answers (1)

Divakar
Divakar

Reputation: 221514

You could use broadcasting -

(np.abs(A[:,None,:] - A)).sum(axis=(0,1))

Steps :

(1) Keeping the last axis aligned get two versions of A :

Input1 (A[:,None,:])    :  M x 1 x N
Input2 (A)              :      M x N

Get the absolution differences between these two inputs resulting in a 3D array.

(2) Sum along the first two axes for final output.

Upvotes: 1

Related Questions