2

How can I replace array values in place if I don't know the axis beforehand?

For example, if I wanna do something like

arr[:,5]

but I don't know the axis beforehand and want to make it general I can use take:

arr.take(5, axis=1)

and it'll work.

However, if I want to something like

arr[:,5]=10

but I don't know the axis beforehand, how can I do it? I obviously can't do arr.take(5, axis=1) = 10, and I can't find a function to do it.

The function that comes the closest (that I found) would be np.put(), but I don't think it can be done with that.

2 Answers 2

3

You could swap the desired axis to the first position and then do the assignment. swapaxes returns a view, so the assignment will do what you want.

For example,

In [87]: np.random.seed(123)

In [88]: a = np.random.randint(1, 9, size=(5, 8))

In [89]: a
Out[89]: 
array([[7, 6, 7, 3, 5, 3, 7, 2],
       [4, 3, 4, 2, 7, 2, 1, 2],
       [7, 8, 2, 1, 7, 1, 8, 2],
       [4, 7, 6, 5, 1, 1, 5, 2],
       [8, 4, 3, 5, 8, 3, 5, 8]])

In [90]: ax = 1

In [91]: k = 5

In [92]: val = 99

In [93]: a.swapaxes(0, ax)[k] = val

In [94]: a
Out[94]: 
array([[ 7,  6,  7,  3,  5, 99,  7,  2],
       [ 4,  3,  4,  2,  7, 99,  1,  2],
       [ 7,  8,  2,  1,  7, 99,  8,  2],
       [ 4,  7,  6,  5,  1, 99,  5,  2],
       [ 8,  4,  3,  5,  8, 99,  5,  8]])

In [95]: ax = 0

In [96]: k = 2

In [97]: val = -1

In [98]: a.swapaxes(0, ax)[k] = val

In [99]: a
Out[99]: 
array([[ 7,  6,  7,  3,  5, 99,  7,  2],
       [ 4,  3,  4,  2,  7, 99,  1,  2],
       [-1, -1, -1, -1, -1, -1, -1, -1],
       [ 4,  7,  6,  5,  1, 99,  5,  2],
       [ 8,  4,  3,  5,  8, 99,  5,  8]])
Sign up to request clarification or add additional context in comments.

Comments

2

I don't think there is a NumPy function for this, but it is not too hard to construct your own:

def replace(arr, indices, val, axis):
    s = [slice(None)]*arr.ndim
    s[axis] = indices
    arr[s] = val

import numpy as np

def replace(arr, indices, val, axis):
    s = [slice(None)]*arr.ndim
    s[axis] = indices
    arr[s] = val

arr = np.zeros((3,6,2))
indices = 5
axis = 1
val = 10

replace(arr, indices, val, axis)
print(np.take(arr, indices, axis))

prints

[[ 10.  10.]
 [ 10.  10.]
 [ 10.  10.]]

2 Comments

"replace" is already a method for several classes. I would recommend another name.
@Acccumulation: Okay, but then what would you suggest?

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.