0

Say I have this array

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

and

y = np.array([4,5,6])

I'd like x to become

[4,4,4
 5,5,5
 6,6,6]

meaning, i in x becomes y[i]. I have a feeling fancy indexing will be my help, but I'm new to numpy and struggling.


input;

[[  0   0   0 ... 255 255 255]
 [  0   0   0 ... 255 255 255]
 [  0   0   0 ... 255 255 255]
 ...
 [  0   0   0 ... 255 255 255]
 [  0   0   0 ... 255 255 255]
 [  0   0   0 ... 255 255 255]]

and my desired output, given y of length 256, y = np.array([5,6,7.......261])

[[  5    ... 261]
 [  5    ... 261]
 [  5    ... 261]
 ...
 [  5    ... 261]
 [  5    ... 261]
 [  5    ... 261]]
2
  • Please provide a small working example (input and expected output) Commented Oct 27, 2020 at 15:00
  • @RiccardoBucco Done, I think this covers everything Commented Oct 27, 2020 at 15:08

2 Answers 2

1

If you have (which I think you want):

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

y = np.array([4,5,6])

then:

y[x]

Out: 
array([[4, 4, 4],
       [5, 5, 5],
       [6, 6, 6]])

That's . . . just how indexing works :)

Sign up to request clarification or add additional context in comments.

1 Comment

Wow do I feel dumb. this is perfect!
1

You can use np.repeat:

>>> np.repeat(y, x.size / y.size)
array([4, 4, 4, 5, 5, 5, 6, 6, 6])

3 Comments

Thanks for the reply. Will this works for 2D arrays as well?
@Omri.B Please update your question with the desired details and I'll work on it
Edited. Tried to simplify it but went too far.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.