【问题标题】:What is the use of the data type intp?数据类型 intp 有什么用?
【发布时间】:2020-08-26 06:29:09
【问题描述】:

数据类型intp见下表:

另外,索引是什么意思?

【问题讨论】:

标签: python numpy cpython


【解决方案1】:

整数数组索引

整数数组索引允许根据它们的 N 维索引选择数组中的任意项。每个整数数组表示该维度的多个索引。 纯整数数组索引

当索引由与被索引数组的维度一样多的整数数组组成时,索引是直截了当的,但与切片不同。

高级索引总是作为一个广播和迭代:

result[i_1, ..., i_M] == x[ind_1[i_1, ..., i_M], ind_2[i_1, ..., i_M],
                           ..., ind_N[i_1, ..., i_M]]

请注意,结果形状与(广播)索引数组形状 ind_1、...、ind_N 相同。

例子

应从每一行中选择一个特定元素。行索引只是 [0, 1, 2],列索引指定要为相应行选择的元素,这里是 [0, 1, 0]。将两者结合使用,可以使用高级索引来解决任务:

x = np.array([[1, 2], [3, 4], [5, 6]])

x[[0, 1, 2], [0, 1, 0]]
array([1, 4, 5])

要实现类似于上述基本切片的行为,可以使用广播。函数 ix_ 可以帮助进行这种广播。最好通过一个例子来理解这一点。

例子

应使用高级索引从 4x3 数组中选择角元素。因此,需要选择列是 [0, 2] 之一并且行是 [0, 3] 之一的所有元素。要使用高级索引,需要明确选择所有元素。使用前面解释的方法可以这样写:

x = np.array([[ 0,  1,  2],

              [ 3,  4,  5],

              [ 6,  7,  8],

              [ 9, 10, 11]])

rows = np.array([[0, 0],

                 [3, 3]], dtype=np.intp)

columns = np.array([[0, 2],

                    [0, 2]], dtype=np.intp)

x[rows, columns]
array([[ 0,  2],
       [ 9, 11]])

但是,由于上面的索引数组只是重复自己,因此可以使用广播(比较诸如 rows[:, np.newaxis] + columns 之类的操作)来简化这一点:

rows = np.array([0, 3], dtype=np.intp)

columns = np.array([0, 2], dtype=np.intp)

rows[:, np.newaxis]
array([[0],
       [3]])

x[rows[:, np.newaxis], columns]
array([[ 0,  2],
       [ 9, 11]])

这种广播也可以使用函数ix_来实现:

x[np.ix_(rows, columns)]
array([[ 0,  2],
       [ 9, 11]])

请注意,如果没有 np.ix_ 调用,则只会选择对角线元素,就像前面示例中使用的那样。这种差异是使用多个高级索引进行索引时要记住的最重要的事情。

请阅读。

参考号:https://numpy.org/doc/stable/reference/arrays.indexing.html

【讨论】:

  • 但是你不需要为 ``rows` 和 columns 指定 intp dtype。 np.array([0,3]) 就够了。
猜你喜欢
  • 2018-03-16
  • 2019-09-17
  • 1970-01-01
  • 2011-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多