I have an array which looks like this for example:
array([[ 1, 1, 2, 0, 4],
[ 5, 6, 7, 8, 9],
[10, 0, 0, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 0, 24],
[25, 26, 27, 28, 29],
[30, 31, 32, 33, 34],
[35, 36, 37, 38, 39],
[40, 41, 42, 43, 44],
[45, 46, 47, 48, 49]])
I have another two arrays which are like:
array([[ 0, 0, 0, 0],
[ 0, 0, 0, 0],
[ 0, 2891, 0, 0],
[ 0, 0, 0, 0],
[ 0, 0, 0, 2891]])
and
array([[ 0, 0, 0, 643],
[ 0, 0, 0, 0],
[ 0, 0, 643, 0],
[ 0, 0, 0, 0],
[ 0, 0, 0, 0]])
What I want is to pick value 2891 from the 2nd array to the first array in the corresponding position and also 643 from the third array to the first array in the corresponding position so that the final array should look like this:
array([[ 1, 1, 2, 643, 4],
[ 5, 6, 7, 8, 9],
[ 10, 2891, 643, 13, 14],
[ 15, 16, 17, 18, 19],
[ 20, 21, 22, 2891, 24],
[ 25, 26, 27, 28, 29],
[ 30, 31, 32, 33, 34],
[ 35, 36, 37, 38, 39],
[ 40, 41, 42, 43, 44],
[ 45, 46, 47, 48, 49]])
So far I have tried this command:
np.place(a,a<1, np.amax(b))
where a
referred to the first array and b
referred to the 2nd array. What it does it just replace all the 0 value with 2891 value. Can someone help?
We can replace values inside the list using slicing. First, we find the index of variable that we want to replace and store it in variable 'i'. Then, we replace that item with a new value using list slicing.
To replace a row in an array we will use the slicing and * operator method. It will help the user for replacing rows elements. Firstly we will import the numpy library and then create a numpy array by using the np. array() function.
You can find the indices where y
and z
are nonzero using the nonzero method:
In [9]: y.nonzero()
Out[9]: (array([2, 4]), array([1, 3]))
In [10]: z.nonzero()
Out[10]: (array([0, 2]), array([3, 2]))
You can select the associated values through fancing indexing:
In [11]: y[y.nonzero()]
Out[11]: array([2891, 2891])
and you can assign these values to locations in x
with
In [13]: x[y.nonzero()] = y[y.nonzero()]
import numpy as np
x = np.array([[ 1, 1, 2, 0, 4],
[ 5, 6, 7, 8, 9],
[10, 0, 0, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 0, 24],
[25, 26, 27, 28, 29],
[30, 31, 32, 33, 34],
[35, 36, 37, 38, 39],
[40, 41, 42, 43, 44],
[45, 46, 47, 48, 49]])
y = np.array([[ 0, 0, 0, 0],
[ 0, 0, 0, 0],
[ 0, 2891, 0, 0],
[ 0, 0, 0, 0],
[ 0, 0, 0, 2891]])
z = np.array([[ 0, 0, 0, 643],
[ 0, 0, 0, 0],
[ 0, 0, 643, 0],
[ 0, 0, 0, 0],
[ 0, 0, 0, 0]])
x[y.nonzero()] = y[y.nonzero()]
x[z.nonzero()] = z[z.nonzero()]
print(x)
yields
[[ 1 1 2 643 4]
[ 5 6 7 8 9]
[ 10 2891 643 13 14]
[ 15 16 17 18 19]
[ 20 21 22 2891 24]
[ 25 26 27 28 29]
[ 30 31 32 33 34]
[ 35 36 37 38 39]
[ 40 41 42 43 44]
[ 45 46 47 48 49]]
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