gpt4 book ai didi

python - 拉伸(stretch)数组并填充 nan

转载 作者:行者123 更新时间:2023-11-28 22:13:03 25 4
gpt4 key购买 nike

我有一个长度为 n 的一维 numpy 数组,我想将它拉伸(stretch)到 m (n

例如:

>>> 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.两端没有nan(如果可能的话)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),是否有解决此问题的线索?

最佳答案

使用 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 生成的数组比 gaps 多一个数组,roundrobin-ing(即交替迭代)授予 np.nan 永远不会在结果的两端。

关于python - 拉伸(stretch)数组并填充 nan,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54304035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com