Add value to each element in python array

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 of the array. I want my result to return array 4, for example

 array([[1, 1],[2, 3]]) array([[0, 2],[2, 3]]) array([[0, 1],[3, 3]]) array([[0, 1],[2, 4]]) 
+6
source share
2 answers
 [a + i.reshape(2, 2) for i in np.identity(4)] 
+5
source

Assuming a as an input array to add values ​​to, and val 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)) 

Run Example -

 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 want to create separate arrays from out , you can use an additional step: np.array_split(out,a.size) . But for efficiency, I would recommend using indexing to access all such submatrices as out[0] (for the first submatrix), out[1] (for the second submatrix), etc.

+1
source

Source: https://habr.com/ru/post/989081/


All Articles