繁体   English   中英

使用冒号的 Numpy 数组切片

[英]Numpy array slicing using colons

我正在尝试学习 numpy 数组切片。

但这是我似乎无法理解的语法。

有什么作用

a[:1]做。

我在 python 中运行它。

a = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])
a = a.reshape(2,2,2,2)
a[:1]

输出:

array([[[ 5,  6],
        [ 7,  8]],

       [[13, 14],
        [15, 16]]])

有人可以向我解释切片及其工作原理。 文档似乎没有回答这个问题。

另一个问题是有没有办法使用类似的东西生成数组

np.array(1:16)或类似在 python 中的东西

x = [x for x in range(16)]

切片中的逗号用于分隔您可能拥有的各种维度。 在您的第一个示例中,您将数据重塑为具有 4 个维度,每个维度的长度为 2。这可能有点难以可视化,因此如果您从 2D 结构开始,它可能更有意义:

>>> a = np.arange(16).reshape((4, 4))
>>> a
    array([[ 0,  1,  2,  3],
           [ 4,  5,  6,  7],
           [ 8,  9, 10, 11],
           [12, 13, 14, 15]])
>>> a[0]  # access the first "row" of data
    array([0, 1, 2, 3])
>>> a[0, 2]  # access the 3rd column (index 2) in the first row of the data
    2

如果要使用切片访问多个值,可以使用冒号来表示范围:

>>> a[:, 1]  # get the entire 2nd (index 1) column
    array([[1, 5, 9, 13]])
>>> a[1:3, -1]  # get the second and third elements from the last column
    array([ 7, 11])
>>> a[1:3, 1:3]  # get the data in the second and third rows and columns
    array([[ 5,  6],
           [ 9, 10]])

您也可以执行以下步骤:

>>> a[::2, ::2]  # get every other element (column-wise and row-wise)
    array([[ 0,  2],
          [ 8, 10]])

希望有帮助。 一旦这更有意义,您可以通过使用Nonenp.newaxis或使用...省略号来查看诸如添加维度之类的内容:

>>> a[:, None].shape
    (4, 1, 4)

您可以在此处找到更多信息: http : //docs.scipy.org/doc/numpy/reference/arrays.indexing.html

随着我们的进行,探索shape和单个条目可能是值得的。

让我们开始

>>> a = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])
>>> a.shape
(16, )

这是一个长度为 16 的一维数组。

现在让我们试试

>>> a = a.reshape(2,2,2,2)
>>> a.shape
(2, 2, 2, 2)

它是一个 4 维的多维数组。

让我们看看 0, 1 元素:

>>> a[0, 1]
array([[5, 6],
   [7, 8]])

由于剩下两个维度,它是一个二维矩阵。


现在, a[:, 1]说:取a[i, 1对所有可能的值i

>>> a[:, 1]
array([[[ 5,  6],
    [ 7,  8]],

   [[13, 14],
    [15, 16]]])

它为您提供了一个数组,其中第一项是a[0, 1] ,第二项是a[1, 1]

要回答问题的第二部分(生成顺序值数组),您可以使用np.arange(start, stop, step)np.linspace(start, stop, num_elements) 这两个都返回一个具有相应值范围的 numpy 数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM