【问题标题】:Slicing array returns strange shape切片数组返回奇怪的形状
【发布时间】:2018-02-08 19:47:06
【问题描述】:

假设我在 Ipython 中执行以下操作:

import numpy as np
test = np.zeros([3,2])
test
test.shape
test[:,0]
test[:,0].shape

结果将是:

array([[ 0.,  0.],
       [ 0.,  0.],
       [ 0.,  0.]])
(3,2)
array([ 0.,  0.,  0.])
(3,)

为什么这里的最后一个结果不是(3,1)?我有一个解决方法:reshape 命令,但这似乎很愚蠢。

【问题讨论】:

  • 使用切片来保持维度。 test[:,:1].
  • 返回 (3,1) 的形状。但如果我想要一个不同的列,并尝试test[:,:0],我会得到 (3,0) 的形状。
  • 你想要哪一栏?要获取第 i 列,test[:,i:i+1]
  • NumPy 不是矩阵库。它是一个 n 维数组库。 test[:, 0] 是一维数组。
  • 在 MATLAB 中像这样对 (n)d 矩阵进行索引会将维度减少到 (n-1)d,因为 n>2。 numpy 做同样的事情,只是它没有人为的 2 最小维度。

标签: python python-3.x numpy slice reshape


【解决方案1】:

我使用不同的数组进行可视化:

>>> import numpy as np
>>> test = np.arange(6).reshape(3, 2)
>>> test
array([[0, 1],
       [2, 3],
       [4, 5]])

像这样切片:

>>> test[:,0]
array([0, 2, 4])

告诉 NumPy 保留第一个维度,但只取第二个维度的第一个元素。根据定义,这会将维数减少 1。

就像:

>>> test[0, 0]
0

将采用第一个维度的第一个元素和第二个维度的第一个元素。从而将维数减少了 2。

如果您想将第一列作为实际列(不改变维数),您需要使用切片:

>>> test[:, 0:1]  # remember that the stop is exlusive so this will get the first column only
array([[0],
       [2],
       [4]])

或类似

>>> test[:, 1:2]  # for the second column
array([[1],
       [3],
       [5]])

>>> test[0:1, :]  # first row
array([[0, 1]])

【讨论】:

  • 太棒了!感谢您的帮助!
【解决方案2】:

如果您在给定维度中只有一个坐标但想要保留该维度,请将其包装在 arraylist

test[:,[0]].shape
Out: (3, 1)

【讨论】:

    猜你喜欢
    • 2015-10-03
    • 1970-01-01
    • 1970-01-01
    • 2012-12-21
    • 2014-11-26
    • 2020-04-25
    • 2019-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多