How can I manipulate a copy of an array without changing the original array?

Viewed 2653

I have an array called n with numbers, and my goal is to make an array m where m[i] = n[i] - n[i-1]. m[0] is just equal to n[0]. I've tried this:

import numpy as np
n = np.array([1,2,3,4])
m = n
for i in range(1, len(n)):
    m[i] = n[i] - n[i-1]

The assignment in the for loop does something I don't understand, because it makes both n and m into arrays = [1 1 2 2]. I simply want to change the inputs in m.

Note: My code does as I want it to when I strictly initialize both n and m like this:

n = np.array([1,2,3,4])
m = np.array([1,2,3,4])

But I feel like I should be able to make a copy of n and be able to to manipulate ONLY the copy. Any suggestions or help?

4 Answers

By doing m = n, you're simply binding a new name m to an existing array named n. That's why, when you later make changes to m, you see the same changes applied to n. They both refer to the same object in memory.

To make a copy of the array, you should use the numpy.copy() method:

m = np.copy(n)

Use the copy() method to create a copy and not modify the original array as:

import numpy as np
n = np.array([1,2,3,4])
m = n.copy()
for i in range(1, len(n)):
    m[i] = n[i] - n[i-1]
print(m)
print(n)

Output:

[1 1 1 1]
[1 2 3 4]

Try "m is n" and you will see they are pointing to the same object, not a copy. Variables in Python are just pointers to the underlying objects, so in this example both m and n are pointing to the same array object and modifying it through either of its "names" modifies the same array. You need something like m = n.copy() I am not sure of the exact syntax in numpy.

Use fancy indexing and the power of numpy. Something like this may work

m= n.copy()
m[1:] = n[1:] - n[:-1]
#m[0] = n[0] # not needed because m is originally a copy of n

The n[1:] will create an array with the first element removed, before doing the array sum operation n[:-1] will create an array with the last element removed

Related