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]])
[a + i.reshape(2, 2) for i in np.identity(4)]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With