Splitting an array in numpy

Today I used the numpy array for some calculations and found a strange problem, for example, suppose I already imported numpy.arange into Ipython and I run several scripts as follows:

In [5]: foo = arange(10) In [8]: foo1 = foo[arange(3)] In [11]: foo1[:] = 0 In [12]: foo Out[12]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) In [16]: foo2 = foo[0:3] In [19]: foo2[:]=0 In [21]: foo Out[21]: array([0, 0, 0, 3, 4, 5, 6, 7, 8, 9]) 

the above shows that when I split the array into foo [arange (3)], I got a copy of the slice of the array, but when I cut the array into foo [0: 3], I got a reference to the slice array, so foo is changed using foo2 . Then I thought that foo and foo2 should have the same identifier, but that is not the case.

 In [59]: id(foo) Out[59]: 27502608 In [60]: id(foo2) Out[60]: 28866880 In [61]: id(foo[0]) Out[61]: 38796768 In [62]: id(foo2[0]) Out[62]: 38813248 ... 

even stranger, if I keep checking id foo and foo2, they are not constant, and sometimes they match each other!

 In [65]: id(foo2[0]) Out[65]: 38928592 In [66]: id(foo[0]) Out[66]: 37111504 In [67]: id(foo[0]) Out[67]: 38928592 

Can someone explain this a bit? I am really confused by this dynamic python function

thanks alot

+6
source share
1 answer
 foo[arange(3)] 

not a slice. arange(3) elements are used to select foo elements to build a new array. Since this cannot effectively return the view (each element of the view must be an independent reference, and for operations in the view it will take too many pointers), it returns a new array.

 foo[0:3] 

- this is a slice. This can be done effectively as a presentation; it only requires adjustment of some boundaries. Thus, it returns the view.

 id(foo[0]) 

foo[0] does not apply to a specific Python object. Saving separate Python objects for each element of the array would be too expensive, which would negate the great benefits of numpy. Instead, when an indexing operation is performed on numpy ndarray, numpy creates a new object to return. Each time you will receive a different object with a different identifier.

+5
source

Source: https://habr.com/ru/post/956764/


All Articles