如何控制Numpy中空数组的维数(How to control dimensions of empty arrays in Numpy)

编程入门 行业动态 更新时间:2024-10-26 13:22:06
如何控制Numpy中空数组的维数(How to control dimensions of empty arrays in Numpy)

我试图使用numpy在Python中连接一维两个数组。 其中一个数组可能是空的(在这种情况下为a2)。 a1和a2是我无法控制的某些计算的结果。 当a1和a2非空时,它们都具有形式(n,2)的形状,因此连接不是问题。 然而,事实证明其中一个是空的,在这种情况下它的大小变为(0,)。 因此,连接会引发错误。

s1=array(a1).shape s2=array(a2).shape print(s1) #(5,2) print(s2) #(0,) s3=hstack((a1, a2)) s3=concatenate((a1, a2), 0)

错误:ValueError:所有输入数组必须具有相同的维数

我看到其他stackoverflow问题,据说可以连接一个空数组。 如何确保空数组的大小为(0,2)? 有人可以帮我吗?

I was trying to concatenate 1-D two arrays in Python, using numpy. One of the arrays might potentially be empty (a2 in this case). a1 and a2 are the results from some computation over which I have no control. When a1 and a2 are non-empty they both have shapes of the form (n,2), so concatenation is not a problem. However it could turn out that one of them is empty, in which case its size becomes (0,). Hence the concatenation throws up an error.

s1=array(a1).shape s2=array(a2).shape print(s1) #(5,2) print(s2) #(0,) s3=hstack((a1, a2)) s3=concatenate((a1, a2), 0)

Error: ValueError: all the input arrays must have same number of dimensions

I see other stackoverflow questions where it is said that it is possible to concatenate an empty array. How do I ensure that the empty array's size is (0,2)? Can someone help me out?

最满意答案

错误消息告诉您需要知道的内容。 数组是空的还不够 - 它们必须具有相同数量的维度 。 您只关注shape的第一个元素 - 但shape可以有多个元素:

numpy.array([[]]).shape # (1L, 0L) numpy.array([[]]).transpose.shape # (0L, 1L) numpy.array([]).shape # (0L, )

所以你看,空数组可以有不同数量的维度。 这可能是你的问题。

EDIT解决方案创建一个正确大小的空数组是reshape它:

a2.shape() # (0L,) a2 = a2.reshape((0,2)) a2.shape() # (0L, 2L)

这应该可以解决您的问题。

The error message tells you what you need to know. It's not enough that the array is empty - they have to have the same number of dimensions. You are looking only at the first element of shape - but shape can have more than one element:

numpy.array([[]]).shape # (1L, 0L) numpy.array([[]]).transpose.shape # (0L, 1L) numpy.array([]).shape # (0L, )

So you see, empty arrays can have different numbers of dimensions. This may be your problem.

EDIT solution to create an empty array of the right size is to reshape it:

a2.shape() # (0L,) a2 = a2.reshape((0,2)) a2.shape() # (0L, 2L)

This should solve your problem.

更多推荐

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

发布评论

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

>www.elefans.com

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