且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

索引numpy数组和使用整数和numpy标量之间有什么区别?

更新时间:2022-03-23 04:02:34

查看数据缓冲区位置:

In [45]: a.__array_interface__['data']
Out[45]: (44666160, False)
In [46]: a[0].__array_interface__['data']
Out[46]: (44666160, False)

a[0]案例的相同位置.修改a[0]会修改a.

Same location for the a[0] case. Modifying a[0] will modify a.

但是对于数组索引,数据缓冲区是不同的-这是一个副本.修改此副本不会影响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]索引比a[i][j]更惯用.在某些情况下,它们是相同的.但是在很多情况下,它们会有所不同,除非您真的知道它的作用及其原因,否则***避免使用后者.

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]])

使用np.array(0)(一个0d数组)建立索引,就像使用np.array([0])(一个1d数组)建立索引.两者都产生一个副本,其第一维的大小类似于索引.

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.

使用np.matrix时,选择[i][j][i,j]也会影响形状-

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]