Examples of how to replace some elements of a matrix using numpy in python:
Replace some elements of a 1D matrix
Let's try to replace the elements of a matrix called M strictly lower than 5 by the value -1:
>>> import numpy as np
>>> M = np.arange(10)
>>> M
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> M[M > 5 ] = -1
>>> M
array([ 0, 1, 2, 3, 4, 5, -1, -1, -1, -1])
Replace some elements of a 2D matrix
Another example using a 2D matrix
>>> A = np.arange(16)
>>> A
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
>>> A = A.reshape(4,4)
>>> A
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
>>> A[A<=5]=0
>>> A
array([[ 0, 0, 0, 0],
[ 0, 0, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
>>> A[A>1]=1
>>> A
array([[0, 0, 0, 0],
[0, 0, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]])
Using multiple conditions
Exemple using multiple conditions: try to replace the elements > 3 and [HTML REMOVED] 2) & (M < 7)] = -1, illustration:
>>> import numpy as np
>>> M = np.arange(10)
>>> M
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> M[(M > 2) & (M < 7)] = -1
>>> M
array([ 0, 1, 2, -1, -1, -1, -1, 7, 8, 9])
Using the numpy function where
Another solution is to use the numpy function where
>>> A = np.array((1,7,3,8,4,9,1))
>>> np.where(A>4,1,A)
array([1, 1, 3, 1, 4, 1, 1])
References
Links | Site |
---|---|
Replace all elements of Python NumPy Array that are greater than some value | stackoverflow |
Replace “zero-columns” with values from a numpy array | stackoverflow |
numpy.place | numpy doc |
Numpy where function multiple conditions | stackoverflow |
Replace NaN's in NumPy array with closest non-NaN value | stackoverflow |
numpy.put | numpy doc |
numpy.nan_to_num | numpy doc |
How to: Replace values in an array | kite.com |