Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy array divide column by vector

Tags:

python

numpy

I have a 3x3 numpy array and I want to divide each column of this with a vector 3x1. I know how to divide each row by elements of the vector, but am unable to find a solution to divide each column.

like image 801
newdev14 Avatar asked Feb 08 '23 15:02

newdev14


2 Answers

You can transpose your array to divide on each column

(arr_3x3.T/arr_3x1).T
like image 144
C_Z_ Avatar answered Feb 16 '23 04:02

C_Z_


Let's try several things:

In [347]: A=np.arange(9.).reshape(3,3)
In [348]: A
Out[348]: 
array([[ 0.,  1.,  2.],
       [ 3.,  4.,  5.],
       [ 6.,  7.,  8.]])

In [349]: x=10**np.arange(3).reshape(3,1)

In [350]: A/x
Out[350]: 
array([[ 0.  ,  1.  ,  2.  ],
       [ 0.3 ,  0.4 ,  0.5 ],
       [ 0.06,  0.07,  0.08]])

So this has divided each row by a different value

In [351]: A/x.T
Out[351]: 
array([[ 0.  ,  0.1 ,  0.02],
       [ 3.  ,  0.4 ,  0.05],
       [ 6.  ,  0.7 ,  0.08]])

And this has divided each column by a different value

(3,3) divided by (3,1) => replicates x across columns.

With the transpose (1,3) array is replicated across rows.

It's important that x be 2d when using .T (transpose). A (3,) array transposes to a (3,) array - that is, no change.

like image 43
hpaulj Avatar answered Feb 16 '23 02:02

hpaulj