Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numpy

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

like image 462
Shan Avatar asked Feb 20 '26 08:02

Shan


1 Answers

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])
like image 97
Joe Kington Avatar answered Feb 22 '26 21:02

Joe Kington