Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Divide ndarray by its own column indices

I have this numpy ndarray:

myarray = np.array([[[ 1.,  2.,  3.],
                     [ 1.,  2.,  3.]],
                     [[ 4.,  5.,  6.],
                      [ 4.,  5.,  6.]]])

Is there any vector operation I can to do divide each value in the ndarray with (the value's own column index + 1)?

Result I want is

[[[1., 1., 1.],
 [1., 1., 1.]],
 [[4., 2.5, 2.],
 [4., 2.5, 2.]]]

Thanks.

like image 228
Perceptron Avatar asked Dec 20 '25 17:12

Perceptron


1 Answers

You could use NumPy broadcasting for vectorized divisions across all columns, like so -

myarray/(np.arange(myarray.shape[-1])+1)

Sample run -

In [244]: myarray
Out[244]: 
array([[[ 1.,  2.,  3.],
        [ 1.,  2.,  3.]],

       [[ 4.,  5.,  6.],
        [ 4.,  5.,  6.]]])

In [245]: myarray/(np.arange(myarray.shape[-1])+1)
Out[245]: 
array([[[ 1. ,  1. ,  1. ],
        [ 1. ,  1. ,  1. ]],

       [[ 4. ,  2.5,  2. ],
        [ 4. ,  2.5,  2. ]]])
like image 132
Divakar Avatar answered Dec 24 '25 11:12

Divakar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!