gpt4 book ai didi

python - numpy中数组操作的混淆

转载 作者:行者123 更新时间:2023-11-28 20:07:28 25 4
gpt4 key购买 nike

我通常使用 MATLABOctave,最近我切换到 python numpy。在 numpy 中,当我定义这样的数组时

>>> a = np.array([[2,3],[4,5]])

效果很好,数组的大小是

>>> a.shape
(2, 2)

这也与 MATLAB 相同但是当我提取第一个整列并查看大小时

>>> b = a[:,0]
>>> b.shape
(2,)

我得到大小 (2,),这是什么?我希望大小为 (2,1)。也许我误解了基本概念。谁能告诉我这个??

最佳答案

一维 numpy 数组*实际上是一维的——它在任何第二维都没有大小,而在 MATLAB 中,“一维”数组实际上是二维的,其第二维的大小为 1。

如果您希望数组的第二个维度大小为 1,您可以使用其 .reshape() 方法:

a = np.zeros(5,)
print(a.shape)
# (5,)

# explicitly reshape to (5, 1)
print(a.reshape(5, 1).shape)
# (5, 1)

# or use -1 in the first dimension, so that its size in that dimension is
# inferred from its total length
print(a.reshape(-1, 1).shape)
# (5, 1)

编辑

正如 Akavall 指出的那样,我还应该提到 np.newaxis 作为向数组添加新轴的另一种方法。虽然我个人觉得它不太直观,但 np.newaxis 相对于 .reshape() 的一个优点是它允许您以任意顺序添加多个新轴,而无需显式指定输出数组的形状,这对于 .reshape(-1, ...) 技巧是不可能的:

a = np.zeros((3, 4, 5))
print(a[np.newaxis, :, np.newaxis, ..., np.newaxis].shape)
# (1, 3, 1, 4, 5, 1)

np.newaxis 只是 None 的别名,因此您可以使用 a[None, :, None, ...,无]


* 另一方面,np.matrix 始终是二维的,并且会为您提供您在 MATLAB 中熟悉的索引行为:

a = np.matrix([[2, 3], [4, 5]])
print(a[:, 0].shape)
# (2, 1)

有关数组和矩阵之间差异的更多信息,请参阅 here .

关于python - numpy中数组操作的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17139470/

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