Skip to main content
 首页 » 编程设计

python之python数组中None之间的第一个和最后一个数字

2025年05月04日14davidwang456

我有一个像这样的 numpy 数组

[None, None, None, None, None, 8, 7, 2, None, None , None , None, None,  
None, None, 169, 37, 9 ,7 ,23, None , None , 111, 24, 8 7 , 9, 12 , 74, None.......] 

我总是需要在 None 之间的第一个和最后一个值,结果应该是这样的

[8,2,169,23,111,74,...]

有谁知道如何轻松取回这些数字?

请您参考如下方法:

包含 None 和整数的 NumPy 数组无论如何都是 object 类型。 似乎首先使用列表更容易:

res = [] 
for x1, x2 in zip(L[:-1], L[1:]): 
    if (x1 is not None and x2 is None): 
        res.append(x1) 
    elif (x1 is None and x2 is not None):  
        res.append(x2) 

无 res 是:

[8, 2, 169, 23, 111, 74] 

当列表不是以 None 开始或结束时,为了避免错误的结果,将搜索限制在第一个和最后一个 None 之间的部分:

res = [] 
start = L.index(None) 
end = len(L) - L[::-1].index(None) 
 
for x1, x2 in zip(L[start:end-1], L[start+1:end]): 
    if (x1 is not None and x2 is None): 
        res.append(x1) 
    elif (x1 is None and x2 is not None):  
        res.append(x2) 

如果您有一个 NumPy 数组,其中包含 NaN 而不是 None:

a = np.array([np.nan, np.nan, np.nan, np.nan, np.nan, 8, 7, 2, np.nan, 
              np.nan , np.nan , np.nan, np.nan, np.nan, np.nan, 169, 37, 9, 
              7 ,23, np.nan , np.nan , 111, 24, 8, 7 , 9, 12 , 74, np.nan]) 

你可以用向量化的方式来做到这一点:

b = a[np.isnan(np.roll(a, 1)) | np.isnan(np.roll(a, -1))] 
res = b[~np.isnan(b)] 

现在 res 看起来像这样:

array([   8.,    2.,  169.,   23.,  111.,   74.]) 

又是一个限量版 在第一个和最后一个 NaN 之间搜索:

indices = np.arange(len(a))[np.isnan(a)] 
short = a[indices[0]:indices[-1]] 
b = short[np.isnan(np.roll(short, 1)) | np.isnan(np.roll(short, -1))] 
res = b[~np.isnan(b)]