【发布时间】:2019-06-15 16:09:46
【问题描述】:
我有一个长度为 n 的一维 numpy 数组,我想将它拉伸到 m (n 例如: 要求:
1.两端没有nan(如果可能)
2. 全力以赴 我试过了 似乎不能正常工作(对于一个长度为 6553 的数组,违反 req 2,并且不保证 1),有什么线索可以克服这个问题吗?>>> 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
>>> 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,)
【问题讨论】:
-
添加 NaN 背后的逻辑是什么?他们是如何定位的?
-
“系统地”解释它,换句话说,均匀分布(尽可能)。我将以各种方式处理 NaN,这与这个问题无关。
标签: python arrays numpy nan numpy-ndarray