我不理解numpy.array_split
与子指标的行为。实际上,当我考虑给定长度的数组时,我确定了一个子指示,并尝试使用array_split。如果子指数的数量是奇数或偶数,我会得到不同的行为。让我们举个例子
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),而奇数索引的形状命令给出(10,)(假设10个列表)。我实际上有点意外,我想了解原因。我知道当分裂数不等于数组时,也可以使用array_split
。但我想要一些线索,因为我需要在一个循环中插入,如果索引是偶数或奇数,我不知道先验。
答案 0 :(得分:2)
我认为令人惊讶的行为与np.shape
有关,而不是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的一维数组:
In [61]: np.asarray([(1,2),(3,4,5)])
Out[61]: array([(1, 2), (3, 4, 5)], dtype=object)
当array_split
返回等长的数组列表时,np.asarray(a)
会返回一个二维数组:
In [62]: np.asarray([(1,2),(3,4)])
Out[62]:
array([[1, 2],
[3, 4]])