Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does insert and append for numpy ndarray return a new array instead of modifying the original array?

For numpy ndarray, there are no append, and insert as there are for native python lists.

a = np.array([1, 2, 3])
a.append(5)  # this does not work
a = np.append(a, 5)  # this is the only way

Whereas for native python lists,

a = [1, 2, 3]
a.append(4)  # this modifies a
a  # [1, 2, 3, 4]

Why was numpy ndarray designed to be this way? I'm writing a subclass of ndarray, is there any way of implementing "append" like native python arrays?

like image 701
Astral Cai Avatar asked Mar 04 '23 21:03

Astral Cai


1 Answers

NumPy makes heavy use of views, a feature that Python lists do not support. A view is an array that uses the memory of another object rather than owning its own memory; for example, in the following snippet

a = numpy.arange(5)
b = a[1:3]

b is a view of a.

Views would interact very poorly with an in-place append or other in-place size-changing operations. Arrays would suddenly not be views of arrays they should be views of, or they would be views of deallocated memory, or it would be unpredictable whether an append on one array would affect an array it was a view of, or all sorts of other problems. For example, what would a look like after b.append(6)? Or what would b look like after a.clear()? And what kind of performance guarantees could you make? Probably not the amortized constant time guarantee of list.append.

If you want to append, you probably shouldn't be using NumPy arrays; you should use a list, and build an array from the list when you're done appending.

like image 166
user2357112 supports Monica Avatar answered Apr 27 '23 00:04

user2357112 supports Monica