Home > OS >  Replace element of a 3X4 matrix by value from another array
Replace element of a 3X4 matrix by value from another array

Time:10-06

I have a 3x4 matrix and I want to replace the element in the matrix if it meets certain condition (say >0.5 here) with the value that in the same axis=1. Should I slice the matrix or is there a better way?

matrix = np.array([[0.1, 0.9, 0.9, 0],
                    [0.8, 0.2, 0, 0.1],
                    [0.2, 0.1, 0, 0]])
array = np.array([['a', 'b', 'c', 'd'])

Expected Results:

([[0.1, b, c, 0],
[a, 0.2, 0, 0.1],
[0.2, 0.1, 0, 0]])

CodePudding user response:

Use numpy.where:

rows, columns = np.where(matrix > 0.5)
matrix = matrix.astype(object)  # need it to set the string values
matrix[rows, columns] = array[columns]
print(matrix)

Output

[[0.1 'b' 'c' 0.0]
 ['a' 0.2 0.0 0.1]
 [0.2 0.1 0.0 0.0]]
  • Related