Skip to main content
 首页 » 编程设计

python之numpy array_split 的奇怪行为

2024年10月25日8EasonJim

我不理解带有子索引的 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),而在奇数索引的情况下,shape 命令给出了 (10,)(假定的 10 个列表)。实际上我有点惊讶,我想了解原因。我知道 array_split 也可以在拆分次数不能均分数组时使用。但我也想要一些线索,因为我需要插入一个循环,在这个循环中我事先不知道索引是偶数还是奇数。

请您参考如下方法:

我认为与 np.array_split 相比,与 np.shape 更多有关:

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) 是一维的对象数据类型数组:

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]])