gpt4 book ai didi

python - np.array[ :, 0] 和 np.array[ :, [0]] 有什么区别?

转载 作者:行者123 更新时间:2023-11-30 22:20:22 26 4
gpt4 key购买 nike

我有一个 numpy 数组 cols2:

print(type(cols2))
print(cols2.shape)
<class 'numpy.ndarray'>
(97, 2)

我试图使用下面的第一个代码获取这个 2d numpy 数组的第一列,然后我得到一个向量而不是我理想的一列数据。第二个代码似乎给了我理想的答案,但我很困惑第二个代码通过在零之外添加括号来做什么?

print(type(cols2[:,0]))
print(cols2[:,0].shape)
<class 'numpy.ndarray'>
(97,)

print(type(cols2[:,[0]]))
print(cols2[:,[0]].shape)
<class 'numpy.ndarray'>
(97, 1)

最佳答案

cols2[:, 0] 指定您要从 2D 数组中切出长度为 97 的 1D 向量。 cols2[:, [0]] 指定您要从 2D 数组中切出形状为 (97, 1) 的 2D 子数组。方括号 [] 在这里起到了重要作用。

v = np.arange(6).reshape(-1, 2)

v[:, 0]
array([0, 2, 4])

v[:, [0]]
array([[0],
[2],
[4]])

根本的区别是后一个命令中的额外维度(正如您所注意到的)。这是预期的行为,在 numpy.ndarray.__get/setitem__ 中实现并在 NumPy 文档中进行了编码。

您还可以指定 cols2[:,0:1] 达到相同的效果 - 列子切片。

v[:, 0:1]
array([[0],
[2],
[4]])

有关更多信息,请查看 Advanced Indexing 上的注释在 NumPy 文档中。

关于python - np.array[ :, 0] 和 np.array[ :, [0]] 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48858377/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com