numpy array

编程入门 行业动态 更新时间:2024-10-13 08:20:40
本文介绍了numpy array_split的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我不了解numpy.array_split与子索引的行为.确实,当我考虑给定长度的数组时,我确定了一个子索引,然后尝试使用array_split.如果子索引的数量是奇数或偶数,则我会得到不同的行为.让我们举个例子吧

I do not understand the behaviour of numpy.array_split with subindices. Indeed when I consider an array of a given length, I determine a subindices and I try to use array_split. I obtain different behaviour if the number of subindices is odd or even. Let's make an example

import numpy as np a = np.ones(2750001) # fake array t = np.arange(a.size) # fake time basis indA = ((t>= 5e5) & (t<= 1e6)) # First subindices odd number indB = ((t>=5e5+1) & (t<= 1e6)) # Second indices even number # now perform array_split print(np.shape(np.array_split(a[indA],10))) # (10,) print(np.shape(np.array_split(a[indB],10))) # (10, 50000)

现在我们得到不同的结果,基本上对于shape命令实际上给出的偶数为(10,50000),而对于奇数索引,shape命令给出的结果为(10,)(假设有10个列表).实际上,我有点惊讶,我想了解原因.我知道array_split也可以在分割数不相等地分割数组时使用.但是我还想提供一些线索,因为我需要在一个循环中插入一个不知道先验索引是偶数还是偶数的循环.

Now we have different results, basically for the even number we have that the shape command gives actually (10,50000) whereas the shape command in case of odd indices gives (10,) (the 10 lists supposed). I'm a bit surprise actually and I would like to understand the reason. I know that array_split can be used also when the number of splitting does not equally divide the array. But I would like some clue also because I need to insert in a loop where I do not know a priori if the indices will be even or odd.

推荐答案

我认为令人惊讶的行为与np.shape的关系要大于np.array_split:

I think the suprising behavior has more to do with np.shape than np.array_split:

In [58]: np.shape([(1,2),(3,4)]) Out[58]: (2, 2) In [59]: np.shape([(1,2),(3,4,5)]) Out[59]: (2,)

np.shape(a) 显示数组np.asarray(a)的形状:

def shape(a): try: result = a.shape except AttributeError: result = asarray(a).shape return result

因此,当np.array_split返回长度不等的数组时,np.asarray(a)是对象dtype的一维数组:

So, when np.array_split returns a list of arrays of unequal length, np.asarray(a) is a 1-dimensional array of object dtype:

In [61]: np.asarray([(1,2),(3,4,5)]) Out[61]: array([(1, 2), (3, 4, 5)], dtype=object)

当array_split返回等长长度数组 的列表时,np.asarray(a)返回二维数组:

When array_split returns a list of arrays of equal length, then np.asarray(a) returns a 2-dimensional array:

In [62]: np.asarray([(1,2),(3,4)]) Out[62]: array([[1, 2], [3, 4]])

更多推荐

numpy array

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

发布评论

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

>www.elefans.com

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