(n,1)和(n,)的numpy数组 [英] numpy array that is (n,1) and (n,)

查看:177
本文介绍了(n,1)和(n,)的numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

形状为(N,1)和(N,)的numpy数组(让我们说X)有什么区别.它们不是Nx1矩阵吗?我问的原因是因为有时计算会返回一个或另一个.

What is the difference between a numpy array (lets say X) that has a shape of (N,1) and (N,). Aren't both of them Nx1 matrices ? The reason I ask is because sometimes computations return either one or the other.

推荐答案

这是一维数组:

>>> np.array([1, 2, 3]).shape
(3,)

此数组是2D数组,但在第一维中只有一个元素:

This array is a 2D but there is only one element in the first dimension:

>>> np.array([[1, 2, 3]]).shape
(1, 3)

移调给出您要的形状:

>>> np.array([[1, 2, 3]]).T.shape
(3, 1)

现在,看一下数组.仅填充此2D数组的第一列.

Now, look at the array. Only the first column of this 2D array is filled.

>>> np.array([[1, 2, 3]]).T
array([[1],
       [2],
       [3]])

给出以下两个数组:

>>> a = np.array([[1, 2, 3]])
>>> b = np.array([[1, 2, 3]]).T
>>> a
array([[1, 2, 3]])
>>> b
array([[1],
       [2],
       [3]])

您可以利用广播的优势:

You can take advantage of broadcasting:

>>> a * b
array([[1, 2, 3],
       [2, 4, 6],
       [3, 6, 9]])

缺少的数字已填写.请考虑表格或电子表格中的行和列.

The missing numbers are filled in. Think for rows and columns in table or spreadsheet.

>>> a + b
array([[2, 3, 4],
       [3, 4, 5],
       [4, 5, 6]]) 

以更大的尺寸执行此操作会使您的想象力变得更困难.

Doing this with higher dimensions gets tougher on your imagination.

这篇关于(n,1)和(n,)的numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆