Numpy - Why Z[(0,2)] Can Be View For Some Cases And Be Copy In The Others?
Continuation to the question numpy - why Z[(0,2)] is view but Z[(0, 2), (0)] is copy?. I got the answer and understood that comma triggering advanced index makes a totally differen
Solution 1:
In [195]: Y = np.arange(12).reshape(3,4)
In [196]: Y
Out[196]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
Using 2 scalar indices on a 2d array returns one element from the array, a numpy
scalar.
In [197]: Y[0,1]
Out[197]: 1
In [198]: type(_)
Out[198]: numpy.int64
For most purposes we can view such an object as Python integer. It does have ndarray
like attributes such as shape
and even __array_interface__
, but it is not a ndarray
.
In contrast a 'slice' of an array itself an array:
In [199]: Y[0,:]
Out[199]: array([0, 1, 2, 3])
In [200]: type(_)
Out[200]: numpy.ndarray
https://numpy.org/doc/stable/reference/arrays.scalars.html
This docs has a small section showing how an array scalar can be treated as a 0d array.
In [209]: Y.__array_interface__['data']
Out[209]: (38135024, False)
In [210]: Y[0,0].__array_interface__['data']
Out[210]: (35130688, False)
In [211]: Y[0,0,...].__array_interface__['data']
Out[211]: (38135024, False)
In [212]: Y[0,0] # array scalar
Out[212]: 0
In [213]: Y[0,0,...] # 0d array
Out[213]: array(0)
To get an element of the array, as a 'plain' Python type:
In [215]: Y.item(0,0)
Out[215]: 0
In [216]: type(_)
Out[216]: int
Post a Comment for "Numpy - Why Z[(0,2)] Can Be View For Some Cases And Be Copy In The Others?"