从二维数组中切出一列

我有以下代码:


import numpy as np

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

              [ 7,  8,  9, 10, 11, 12]])

a[:, 2:3] #get [[[3],[9]]

a[:,[2]] # get [[3],[9]]

a[:, 2, None] # get [[3],[9]]

a[:, 2] #get [3, 9]

为什么a[:, 2]得到 [3, 9] ?


ps 看到一些帖子讨论从 2D 数组中切出 1 列(如上例所示)得到一个 1D 数组,但没有对why.


pps 这个问题不是关于how-to做,而是why做。


白衣非少年
浏览 202回答 2
2回答

森栏

Numpy 正在删除第二个示例中的单例维度。如果需要,您可以保留形状并使用以下内容获得第一个示例的等效项。a[:, [2]] # get [[3],[9]]

湖上湖

我认为您1D以稍微不明确的方式使用术语数组。第一个选项返回形状为 (2, 1) 的数组,另一个选项返回形状为 (2, ) 的类似列表的数组。它们都是“数学上”一维的,但它们具有不同的麻木形状。所以你的目标是获得一个更像矩阵的数组,形状为 (2, 1),这是通过在所有维度上切片所需的索引来完成的,而不是选择特定的索引。这是一个更直观的案例,可以通过在两个维度上进行切片或选择来将事情发挥到极致:import numpy as npa = np.array([[ 1,&nbsp; 2,&nbsp; 3,&nbsp; 4,&nbsp; 5,&nbsp; 6],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;[ 7,&nbsp; 8,&nbsp; 9, 10, 11, 12]])specific_index_value = a[0, 0]print(specific_index_value)print(type(specific_index_value))print(str(specific_index_value) + ' is a scalar, not a 1X1 matrix')>> 1>> <class 'numpy.int32'>>> 1 is a scalar, not a 1X1 matrixsliced_index_value = a[:1, :1]print(sliced_index_value)print(type(sliced_index_value))print(str(sliced_index_value) + ' is a matrix, with shape {}'.format(sliced_index_value.shape))>> [[1]]>> <class 'numpy.ndarray'>>> [[1]] is a matrix, with shape (1, 1)那有意义吗?祝你好运!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python