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?
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)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments