我不了解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
发布评论