How to Replace Elements of a Numpy Array with an Array

Asked 2 years ago, Updated 2 years ago, 51 views

I can't think of a way to replace the np.array element with np.array.
For example:

Before Run

img=np.array([
  [0, 1, 2], 
  [2, 1, 1],
])

For example, the value of img[h,w] is

img[h,w]==0 np.array([255,0,0])  
np.array ([125,125,0]) when img[h,w] == 1
np.array ([0,125,125]) when img[h,w] == 2

I would like to replace it with .In other words, for img above,

Post Run

img=np.array([ 
  [[255, 0, 0], [125, 125, 0], [0, 125, 125]],
  [[0, 125, 125], [125, 125, 0], [125, 125, 0]],
])

I'd like to replace it with .
At first, I wondered if I could use np.where, but x,y in np.where(conditions,x,y) has to be a number, and the array seems to be NG.
I look forward to working with you in an efficient way.

python numpy

2022-09-30 18:19

1 Answers

It is efficient to use Fancy Indexing to replace numpy.
See alsoPython Data Science HandbookFancy Indexing

import numpy as np

img = np.array([
    [0, 1, 2], 
    [2, 1, 1],
])    
ind = np.array ([np.array([255,0,0]), np.array([125,125,0]), np.array([0,125,125])])
ind [img]


2022-09-30 18:19

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.