Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpolate only if single NaN

Is there a way in pandas to interpolate only single missing data points? That is, if there is 2+ consecutive NaN's, I'd like to leave them alone.

so, as an example:

s = pd.Series([1, None, 2, 3, None, None, 4.5])
d.interpolate(limit=1)

gives me:

[ 1.0, 1.5, 2.0, 3.0, 3.5, NaN, 4.5 ]

but I'd like to get

[ 1.0, 1.5, 2.0, 3.0, NaN, NaN, 4.5 ]

If it helps, I have a list of the indexes where there are only single missing values.

like image 878
Robert Mah Avatar asked Dec 23 '22 19:12

Robert Mah


1 Answers

My opinion is that this would be a great capability to include in interpolate.
That said, this boils down to masking the places where more than one np.nan exist. I'll wrap that up with some numpy logic in a handy function.

def cnan(s):
    v = s.values
    k = v.size
    n = np.append(np.isnan(v), False)
    m = np.empty(k, np.bool8)
    m.fill(True)
    i = np.where(n[:-1] & n[1:])[0] + np.arange(2)
    m[i[i < k]] = False
    return m

s.interpolate().where(cnan(s))

0    1.0
1    1.5
2    2.0
3    3.0
4    NaN
5    NaN
6    4.5
dtype: float64

For those interested in a general solution using advanced numpy techniques

import pandas as pd
import numpy as np
from numpy.lib.stride_tricks import as_strided as strided

def mask_knans(a, x):
    a = np.asarray(a)
    k = a.size
    n = np.append(np.isnan(a), [False] * (x - 1))
    m = np.empty(k, np.bool8)
    m.fill(True)

    s = n.strides[0]
    i = np.where(strided(n, (k + 1 - x, x), (s, s)).all(1))[0][:, None]
    i = i + np.arange(x)
    i = pd.unique(i[i < k])

    m[i] = False

    return m

demo

a = np.array([1, np.nan, np.nan, np.nan, 3, np.nan, 4, 5, np.nan, np.nan, 6, 7])

print(mask_knans(a, 3))

[ True False False False  True  True  True  True  True  True  True  True]
like image 94
piRSquared Avatar answered Dec 26 '22 12:12

piRSquared