3

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?

plshelp
  • 33
  • 1
  • 4
  • In your original code, `m` is just another reference to the same array object `n` points to. In your second version, `m` and `n` point to different array objects. – couka Feb 11 '21 at 12:40
  • I see, so they're pointing to the same object. Thank you! – plshelp Feb 11 '21 at 12:56

4 Answers4

1

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)
Talendar
  • 1,841
  • 14
  • 23
0

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]
Krishna Chaurasia
  • 8,924
  • 6
  • 22
  • 35
0

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.

eemz
  • 1,183
  • 6
  • 10
0

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

Luis
  • 26
  • 9
  • The big advantage of numpy is that you don't need to use for loops in many of the array operations, and it is much faster this way – Luis Feb 11 '21 at 12:51