这些数组形状之间的差异numpy

编程入门 行业动态 更新时间:2024-10-27 09:43:09
本文介绍了这些数组形状之间的差异numpy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

两个形状为-的数组之间有什么区别?

What is the difference between 2 arrays whose shapes are-

(442,1)和(442,)?

同时打印这两个命令会产生相同的输出,但是当我检查相等性 == 时,会得到一个像这样的2D矢量-

Printing both of these produces an identical output, but when I check for equality ==, I get a 2D vector like this-

array([[ True, False, False, ..., False, False, False], [False, True, False, ..., False, False, False], [False, False, True, ..., False, False, False], ..., [False, False, False, ..., True, False, False], [False, False, False, ..., False, True, False], [False, False, False, ..., False, False, True]], dtype=bool)

有人可以解释其中的区别吗?

Can someone explain the difference?

推荐答案

形状为(442, 1)的数组是二维的.它具有442行和1列.

An array of shape (442, 1) is 2-dimensional. It has 442 rows and 1 column.

形状为(442, )的数组是一维的,由442个元素组成.

An array of shape (442, ) is 1-dimensional and consists of 442 elements.

请注意,他们的代表也应该看起来有所不同.括号的数量和位置有所不同:

Note that their reprs should look different too. There is a difference in the number and placement of parenthesis:

In [7]: np.array([1,2,3]).shape Out[7]: (3,) In [8]: np.array([[1],[2],[3]]).shape Out[8]: (3, 1)

请注意,您可以使用np.squeeze删除长度为1的轴

Note that you could use np.squeeze to remove axes of length 1:

In [13]: np.squeeze(np.array([[1],[2],[3]])).shape Out[13]: (3,)

NumPy广播规则允许自动添加新坐标轴在左侧(如果需要).因此(442,)可以广播到(1, 442).长度为1的轴可以广播到任意长度.所以 当您测试形状为(442, 1)的数组与形状为(442, )的数组之间的相等性时,第二个数组被提升为形状(1, 442),然后两个数组扩展其长度为1的轴,以便它们都成为广播数组形状为(442, 442).这就是为什么当您测试相等性时,结果是形状为(442, 442)的布尔数组.

NumPy broadcasting rules allow new axes to be automatically added on the left when needed. So (442,) can broadcast to (1, 442). And axes of length 1 can broadcast to any length. So when you test for equality between an array of shape (442, 1) and an array of shape (442, ), the second array gets promoted to shape (1, 442) and then the two arrays expand their axes of length 1 so that they both become broadcasted arrays of shape (442, 442). This is why when you tested for equality the result was a boolean array of shape (442, 442).

In [15]: np.array([1,2,3]) == np.array([[1],[2],[3]]) Out[15]: array([[ True, False, False], [False, True, False], [False, False, True]], dtype=bool) In [16]: np.array([1,2,3]) == np.squeeze(np.array([[1],[2],[3]])) Out[16]: array([ True, True, True], dtype=bool)

更多推荐

这些数组形状之间的差异numpy

本文发布于:2023-10-19 19:10:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1508492.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   形状   差异   numpy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!