anon
anon

Reputation:

Subtracting one column from multiple other columns

I have an array of 7 columns and I'm trying to subtract the first column from all the other columns. Right now my code looks like this:

a  = (q[:,0]-q[:,1])**2
a1 = (q[:,0]-q[:,2])**2
a2 = (q[:,0]-q[:,3])**2
a3 = (q[:,0]-q[:,4])**2
a4 = (q[:,0]-q[:,5])**2
a5 = (q[:,0]-q[:,6])**2

This works well except that I'm trying to do this for many files and it is incredibly inefficient. Is there a more efficient way to write this same code?

Thanks

Upvotes: 2

Views: 3552

Answers (1)

wflynny
wflynny

Reputation: 18521

If you want to subtract the first column from all other columns, you can do

import numpy as np
x = np.arange(40).reshape(8, 5) #sample data
y = (x - x[:,0,None])**2

The x[:,0,None] represents the first column. If you just try x - x[:,0], numpy can't broadcast the shapes together ((8, 5) and (8,) in this case). Adding the x[:,0,None] (or x[:,0,np.newaxis]) makes the second shape (8, 1) and numpy can broadcast the two together.

Upvotes: 3

Related Questions