简体   繁体   中英

Strange copy construction of numpy array

The example below is odd to me. Arrays a and c are different, but at modification of the first element of a , the first element of c changes as well. Why is the numpy array implemented like this? If a is assigned as a list, changing the first element of a does not change the first element of c . I cannot think of any example where the behavior of the numpy array would be desired.

import numpy as np

a = np.arange(3,5)
#a = [3, 4]
b = a
c = a[:]
d = a.copy()

print(a is b) # True
print(a is c) # False
print(a is d) # False

print(a, b, c, d) #[3 4] [3 4] [3 4] [3 4]

a[0] = -11.

print(a, b, c, d) #[-11   4] [-11   4] [-11   4] [3 4] HUH?!

Simple Numpy slices return a view , not a copy . As the name implies, a view is backed by the same data, just represented differently. This is part of what makes Numpy so fast, because it doesn't have to create copies of the data every time you slice.

See the docs .

I can't think of a reason why c=a[:] would be useful, but c=a[::2] might be useful. Let's say i get the average of every other element, then increase those by that average.

a=np.random.random(10)
b=a[::2]
b+=b.mean()
print a

There's just no reason to special-case your example to return a copy instead of a view. In fact, it would be quite counter-intuitive to people familiar with how Numpy slices work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM