为了账号安全,请及时绑定邮箱和手机立即绑定

从二维数组中切出一列

从二维数组中切出一列

白衣非少年 2021-09-02 20:56:57
我有以下代码:import numpy as npa = 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做。
查看完整描述

2 回答

?
森栏

TA贡献1810条经验 获得超5个赞

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

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


查看完整回答
反对 回复 2021-09-02
?
湖上湖

TA贡献2003条经验 获得超2个赞

我认为您1D以稍微不明确的方式使用术语数组。

第一个选项返回形状为 (2, 1) 的数组,另一个选项返回形状为 (2, ) 的类似列表的数组。

它们都是“数学上”一维的,但它们具有不同的麻木形状。

所以你的目标是获得一个更像矩阵的数组,形状为 (2, 1),这是通过在所有维度上切片所需的索引来完成的,而不是选择特定的索引。


这是一个更直观的案例,可以通过在两个维度上进行切片或选择来将事情发挥到极致:


import numpy as np

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

             [ 7,  8,  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 matrix


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

那有意义吗?祝你好运!


查看完整回答
反对 回复 2021-09-02
  • 2 回答
  • 0 关注
  • 198 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信