DataFrame.interpolate() 在尾部缺失数据上进行外推

13 投票
3 回答
4664 浏览
提问于 2025-04-18 16:55

考虑以下示例,我们设置了一个样本数据集,创建了一个多重索引,然后将数据框进行“展开”,接着执行线性插值,逐行填充数据:

import pandas as pd  # version 0.14.1
import numpy as np  # version 1.8.1

df = pd.DataFrame({'location': ['a', 'b'] * 5,
                   'trees': ['oaks', 'maples'] * 5,
                   'year': range(2000, 2005) * 2,
                   'value': [np.NaN, 1, np.NaN, 3, 2, np.NaN, 5, np.NaN, np.NaN, np.NaN]})
df.set_index(['trees', 'location', 'year'], inplace=True)
df = df.unstack()
df = df.interpolate(method='linear', axis=1)

展开后的数据集看起来是这样的:

                 value                        
year              2000  2001  2002  2003  2004
trees  location                               
maples b           NaN     1   NaN     3   NaN
oaks   a           NaN     5   NaN   NaN     2

作为一种插值方法,我期待的输出是:

                 value                        
year              2000  2001  2002  2003  2004
trees  location                               
maples b           NaN     1     2     3   NaN
oaks   a           NaN     5     4     3     2

但实际上这个方法给出的结果是(注意这个外推的值):

                 value                        
year              2000  2001  2002  2003  2004
trees  location                               
maples b           NaN     1     2     3     3
oaks   a           NaN     5     4     3     2

有没有办法告诉pandas不要在序列中超出最后一个非缺失值进行外推呢?

编辑:

我还是很希望在pandas中看到这个功能,不过现在我在numpy中实现了这个功能,然后使用df.apply()来修改df。我在pandas中缺少的正是np.interp()中的leftright参数的功能。

def interpolate(a, dec=None):
    """
    :param a: a 1d array to be interpolated
    :param dec: the number of decimal places with which each
                value should be returned
    :return: returns an array of integers or floats
    """

    # default value is the largest number of decimal places in the input array
    if dec is None:
        dec = max_decimal(a)

    # detect array format convert to numpy as necessary
    if type(a) == list:
        t = 'list'
        b = np.asarray(a, dtype='float')
    if type(a) in [pd.Series, np.ndarray]:
        b = a

    # return the row if it's all nan's
    if np.all(np.isnan(b)):
        return a

    # interpolate
    x = np.arange(b.size)
    xp = np.where(~np.isnan(b))[0]
    fp = b[xp]
    interp = np.around(np.interp(x, xp, fp, np.nan, np.nan), decimals=dec)

    # return with proper numerical type formatting
    # check to make sure there aren't nan's before converting to int
    if dec == 0 and np.isnan(np.sum(interp)) == False:
        interp = interp.astype(int)
    if t == 'list':
        return interp.tolist()
    else:
        return interp


# two little helper functions
def count_decimal(i):
    try:
        return int(decimal.Decimal(str(i)).as_tuple().exponent) * -1
    except ValueError:
        return 0


def max_decimal(a):
    m = 0
    for i in a:
        n = count_decimal(i)
        if n > m:
            m = n
    return m

在这个示例数据集上效果很好:

In[1]: df.apply(interpolate, axis=1)
Out[1]:
                 value                        
year              2000  2001  2002  2003  2004
trees  location                               
maples b           NaN     1     2     3   NaN
oaks   a           NaN     5     4     3     2

3 个回答

0

这确实是个让人困惑的功能。这里有一个更简洁的解决方案,可以在最初的插值之后使用。

def de_extrapolate(row):  
    extrap = row[row==row[-1]]    
    if extrap.size > 1:
        first_index = extrap.index[1]
        row[first_index:] = np.nan
    return row

和之前一样,我们有:

In [1]: df.interpolate(axis=1).apply(de_extrapolate, axis=1)
Out[1]: 
                value                    
year             2000 2001 2002 2003 2004
trees  location                          
maples b          NaN    1    2    3  NaN
oaks   a          NaN    5    4    3    2
3

从Pandas版本0.21.0开始,limit_area='inside'这个选项告诉`df.interpolate`只填充那些被有效值包围的空值(NaN):

import pandas as pd  # version 0.21.0
import numpy as np  

df = pd.DataFrame({'location': ['a', 'b'] * 5,
                   'trees': ['oaks', 'maples'] * 5,
                   'year': list(range(2000, 2005)) * 2,
                   'value': [np.NaN, 1, np.NaN, 3, 2, np.NaN, 5, np.NaN, np.NaN, np.NaN]})
df.set_index(['trees', 'location', 'year'], inplace=True)
df = df.unstack()

df2 = df.interpolate(method='linear', axis=1, limit_area='inside')
print(df2)

结果是

                value                    
year             2000 2001 2002 2003 2004
trees  location                          
maples b          NaN  1.0  2.0  3.0  NaN
oaks   a          NaN  5.0  4.0  3.0  2.0
6

把下面这一行:

df = df.interpolate(method='linear', axis=1)

替换成这个:

df = df.interpolate(axis=1).where(df.bfill(axis=1).notnull())

这个代码是用来找到后面连续的空值(NaN)的,它使用了一种叫做“回填”的方法。虽然这个方法不是特别高效,因为它需要进行两次填充操作,但通常来说,这样的问题不会太影响结果。

撰写回答