0

Is there a Numpy operation that does this?

a = np.array([1,2,3])
b = np.some_update_method(a, 0, 99) # b is array([99, 2, 3]), a is unchanged.

In J this is called "amend", but I don't know what it might be called in Numpy (if it exists).

2 Answers 2

1

You can make a copy of the original array and then modify it in place:

b = a.copy()
b[0] = 99

b
# [99  2  3]

a
# [1 2 3]
Sign up to request clarification or add additional context in comments.

1 Comment

Disappointed that Numpy doesn't have a functional amend, but I can wrap this in a function so it will solve my problem. Thanks!
1

Import copy and use deepcopy.

import copy

a = np.array([1,2,3])
b = copy.deepcopy(a)

#modify b

You can use just copy to keep the original the same (the copied elements will be referenced and dependent from the original list), deepcopy will keep each object completely independent, but use twice the memory and whatever time it takes to reproduce the object.

2 Comments

deepcopy is needed only if the array is object dtype. For regular numeric dtype it doesn't do anything more than the copy method. object dtype array are like lists, containing references.
Good to know about when to use deepcopy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.