3

I have a 3D numpy array.

I can modify arbitrary element using simple indexing

D[:,:,0]=myval
D[:,:10,1]=list(range(10))

Sometimes I need to change element(s) at a given index and it is not predetermined at which axis the index refers. I would like to catch the two following cases with a change in variable

D[:,:10,1]=list(range(10)) ->axis 1
D[:10,:,1]=list(range(10)) ->axis 0

Something like:

f(D,axis=0/1,index=1,newval)
2
  • 1
    Look at np.take. Or construct an indexing tuple Commented Nov 8, 2018 at 7:42
  • 1
    @hpaulj np.take wouldn't help with assignment, would it? Commented Nov 8, 2018 at 18:58

1 Answer 1

3

I'd use an indexing tuple with slice objects prepared by the helper object np.s_. If axis is 0 or 1, the following has the effect of assigning list(range(10)) to either D[:10, :, 1] or D[:, :10, 1].

idx = [np.s_[:], np.s_[:], 1] 
idx[axis] = np.s_[:10]
D[tuple(idx)] = list(range(10))
Sign up to request clarification or add additional context in comments.

Comments

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.