Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add value to each element in array python

I have an array like this

a= np.arange(4).reshape(2,2)

array([[0, 1],[2, 3]])

I want to add a value to each element in the array. I want my result return 4 array like

array([[1, 1],[2, 3]])

array([[0, 2],[2, 3]])

array([[0, 1],[3, 3]])

array([[0, 1],[2, 4]])
like image 943
Cheung Shao Yong Avatar asked Jun 14 '15 07:06

Cheung Shao Yong


Video Answer


2 Answers

[a + i.reshape(2, 2) for i in np.identity(4)]
like image 82
enrico.bacis Avatar answered Oct 20 '22 09:10

enrico.bacis


Assuming a as the input array into which values are to be added and val is the scalar value to be added, you can use an approach that works for any multi-dimensional array a using broadcasting and reshaping. Here's the implementation -

shp = a.shape  # Get shape

# Get an array of 1-higher dimension than that of 'a' with vals placed at each
# "incrementing" index  along the entire length(.size) of a and add to a 
out = a  + val*np.identity(a.size).reshape(np.append(-1,shp))

Sample run -

In [437]: a
Out[437]: 
array([[[8, 1],
        [0, 5]],

       [[3, 2],
        [5, 1]]])

In [438]: val
Out[438]: 20

In [439]: out
Out[439]: 
array([[[[ 28.,   1.],
         [  0.,   5.]],
        [[  3.,   2.],
         [  5.,   1.]]],

       [[[  8.,  21.],
         [  0.,   5.]],
        [[  3.,   2.],
         [  5.,   1.]]],

       [[[  8.,   1.],
         [ 20.,   5.]],
        [[  3.,   2.],
         [  5.,   1.]]],

       [[[  8.,   1.],
         [  0.,  25.]],
        [[  3.,   2.],
         [  5.,   1.]]],

       [[[  8.,   1.],
         [  0.,   5.]],
        [[ 23.,   2.],
         [  5.,   1.]]], ....

If you wish to create separate arrays from out, you can use an additional step: np.array_split(out,a.size). But for efficiency, I would advise using indexing to access all those submatrices like out[0] (for the first sub-matrix), out[1] (for the second sub-matrix) and so on.

like image 31
Divakar Avatar answered Oct 20 '22 09:10

Divakar