What's The Difference When Indexing A Numpy Array Between Using An Integer And A Numpy Scalar?
Solution 1:
Looking at the databuffer location:
In[45]: a.__array_interface__['data']Out[45]: (44666160, False)
In[46]: a[0].__array_interface__['data']Out[46]: (44666160, False)
Same location for the a[0]
case. Modifying a[0]
will modify a
.
But with the array index, the data buffer is different - this a copy. Modifying this copy will not affect a
.
In[47]: a[np.array(0)].__array_interface__['data']Out[47]: (43467872, False)
a[i,j]
indexing is more idiomatic than a[i][j]
. In some cases they are the same. But there are enough cases where they differ that it is wise to avoid the later unless you really know what it does, and why.
In[49]: a[0]Out[49]: array([1, 2])
In[50]: a[np.array(0)]Out[50]: array([1, 2])
In[51]: a[np.array([0])]
Out[51]: array([[1, 2]])
Indexing with np.array(0)
, a 0d array, is like indexing with np.array([0])
, a 1d array. Both produce a copy, whose first dimension is sized like the index.
Admittedly this is tricky, and probably doesn't show up except when doing this sort of set.
When using np.matrix
the choice of [i][j]
versus [i,j]
affects shape as well - python difference between the two form of matrix x[i,j] and x[i][j]
Post a Comment for "What's The Difference When Indexing A Numpy Array Between Using An Integer And A Numpy Scalar?"