开发者

how to do linear interpolation on a 2D numpy array having sparse data?

I have a 2D numpy array开发者_高级运维... there are some values in the image and rest is sparse. For linear imterpolation, I want to take the first column of the array. See where the values are present and do the linear interpolation on the zero values but only on one interval.

We loop over every column of the 2D array

As an example, consider following as the first column

   a = [0,0,0,0,1,0,0,0,2,0,0,10,0,0,3,4,6,0,0,1,0,0]

The first four 0,0,0,0 will be the same copy of the first non_zero element in our case this is 1.

The second linear interpolation interval will be

   [1,0,0,0,2]

The third and rest will be

   [2,0,0,10]
   [10,0,0,3]
   [6,0,0,1]

At the end the last element will be copied.

Thanks a lot


Try something like this:

import numpy as np

a = np.array([0,0,0,0,1,0,0,0,2,0,0,10,0,0,3,4,6,0,0,1,0,0])
x, = np.nonzero(a)
a_filled = np.interp(np.arange(a.size), x, a[x])

This yields:

array([1, 1, 1, 1, 1, 1.25, 1.5, 1.75, 2, 4.67, 7.33, 10, 7.67, 5.33, 3, 4, 6, 4.33, 2.67, 1, 1, 1])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜