2

Given an n-dimensional numpy array. Now an axis and corresponding index is given. All elements in that particular axis-index should be replaced by given value. Example of an three-dimensional array:

>>a = np.ones((2,2,2))
array([[[ 1.,  1.],
        [ 1.,  1.]],

        [[ 1.,  1.],
        [ 1.,  1.]]])

Given axis=1, index=0. All elements in this axis-index needs to be zero.

>>a
array([[[ 0.,  0.],
        [ 1.,  1.]],

       [[ 0.,  0.],
        [ 1.,  1.]]])

2 Answers 2

5

Use swapaxes:

a.swapaxes(0, axis)[index] = value

Example:

>>> import numpy as np
>>> a = np.zeros((2,3,4))
>>> a.swapaxes(0, 1)[2] = 3
>>> a
array([[[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [3., 3., 3., 3.]],

       [[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [3., 3., 3., 3.]]])
Sign up to request clarification or add additional context in comments.

Comments

0

you can do a[:,0,:] = 0 and you get your output, where in a[:,0,:] you select index = 0 of the axis=1 and you set the value to 0 over all the other axis

1 Comment

The axis and index are calculated by a program in my case. For your method to work, one needs to know them beforehand.

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.