拉伸阵列并填充nan

问题描述 投票:2回答:4

我有一个长度为n的1-d numpy数组,我想将它拉伸到m(n <m)并系统地添加numpy.nan。

例如:

>>> arr = [4,5,1,2,6,8] # take this
>>> stretch(arr,8)
[4,5,np.nan,1,2,np.nan,6,8] # convert to this

要求:1。两端都没有纳米(如果可能)2。适用于所有长度

我试过了

>>> def stretch(x,to,fill=np.nan):
...     step = to/len(x)
...     output = np.repeat(fill,to)
...     foreign = np.arange(0,to,step).round().astype(int)
...     output[foreign] = x
...     return output

>>> arr = np.random.rand(6553)
>>> stretch(arr,6622)

  File "<ipython-input-216-0202bc39278e>", line 2, in <module>
    stretch(arr,6622)

  File "<ipython-input-211-177ee8bc10a7>", line 9, in stretch
    output[foreign] = x

ValueError: shape mismatch: value array of shape (6553,) could not be broadcast to indexing result of shape (6554,)

似乎没有正常工作(对于长度为6553的数组,违反了要求2,并且不保证1),有什么线索可以克服这个问题吗?

python arrays numpy nan numpy-ndarray
4个回答
2
投票

使用roundrobin from itertools Recipes

from itertools import cycle, islice

def roundrobin(*iterables):
    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    # Recipe credited to George Sakkis
    pending = len(iterables)
    nexts = cycle(iter(it).__next__ for it in iterables)
    while pending:
        try:
            for next in nexts:
                yield next()
        except StopIteration:
            pending -= 1
            nexts = cycle(islice(nexts, pending))

def stretch(x, to, fill=np.nan):
    n_gaps = to - len(x)
    return np.hstack([*roundrobin(np.array_split(x, n_gaps+1), np.repeat(fill, n_gaps))])

arr = [4,5,1,2,6,8]
stretch(arr, 8)
# array([ 4.,  5., nan,  1.,  2., nan,  6.,  8.])

arr2 = np.random.rand(655)
stretched_arr2 = stretch(arr,662)
np.diff(np.argwhere(np.isnan(stretched_arr2)), axis=0)
# nans are evenly spaced    
array([[83],
       [83],
       [83],
       [83],
       [83],
       [83]])

逻辑背后

n_gaps:计算要填充的间隙数(所需长度 - 当前长度)

np_array_split:使用n_gaps+1,它将输入数组分成尽可能相同的长度

roundrobin:因为np_array_split比间隙生成一个阵列,圆形化(即交替迭代)授予np.nan永远不会在结果的任何一端。


1
投票

这种方法将非纳米元素置于边界处,将nan值保留在中心,尽管它不会均匀地分隔nan值。

arr = [4,5,1,2,6,8]   
stretch_len = 8    

def stretch(arr, stretch_len):
    stretched_arr = np.empty(stretch_len)   
    stretched_arr.fill(np.nan)
    arr_len = len(arr)

    if arr_len % 2 == 0:
        mid = int(arr_len/2)
        stretched_arr[:mid] = arr[:mid]
        stretched_arr[-mid:] = arr[-mid:]
    else:
        mid = int(np.floor(arr_len/2))
        stretched_arr[:mid] = arr[:mid]
        stretched_arr[-mid-1:] = arr[-mid-1:]

    return stretched_arr

以下是我测试的一些测试用例:

Test cases:

In [104]: stretch(arr, stretch_len)   
Out[104]: array([ 4.,  5.,  1., nan, nan,  2.,  6.,  8.])

In [105]: arr = [4, 5, 1, 2, 6, 8, 9]    

In [106]: stretch(arr, stretch_len)  
Out[106]: array([ 4.,  5.,  1., nan,  2.,  6.,  8.,  9.])

In [107]: stretch(arr, 9)  
Out[107]: array([ 4.,  5.,  1., nan, nan,  2.,  6.,  8.,  9.])

1
投票

虽然Chris解决了这个问题,但我找到了一个较短的答案,这可能有帮助,

def stretch2(x,to,fill=np.nan):
    output  = np.repeat(fill,to)
    foreign = np.linspace(0,to-1,len(x)).round().astype(int)
    output[foreign] = x
    return output

与我的第一次尝试非常相似。时序:

>>> x = np.random.rand(1000)
>>> to = 1200
>>> %timeit stretch(x,to) # Chris' version
>>> %timeit stretch2(x,to)

996 µs ± 22.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
32.2 µs ± 339 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

检查它是否正常工作:

>>> aa = stretch2(x,to)
>>> np.diff(np.where(np.isnan(aa))[0])
array([6, 6, 6, ... , 6])
>>> np.sum(aa[~np.isnan(aa)] - x)
0.0

检查边界条件:

>>> aa[:5]
array([0.78581616, 0.1630689 , 0.52039993,        nan, 0.89844404])
>>> aa[-5:]
array([0.7063653 ,        nan, 0.2022172 , 0.94604503, 0.91201897])

都很满意。适用于所有1-d阵列,也可以推广使用n-d阵列,只需进行一些更改。


0
投票

您可以使用resize来调整阵列的大小。

一旦调整大小,您可以应用适当的逻辑来重新排列内容。

检查以下链接:https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.resize.html

© www.soinside.com 2019 - 2024. All rights reserved.