首页 文章

在numpy数组中转发NaN值的最有效方法

提问于
浏览
27

示例问题

举个简单的例子,考虑如下定义的numpy数组 arr

import numpy as np
arr = np.array([[5, np.nan, np.nan, 7, 2],
                [3, np.nan, 1, 8, np.nan],
                [4, 9, 6, np.nan, np.nan]])

其中 arr 在控制台输出中如下所示:

array([[  5.,  nan,  nan,   7.,   2.],
       [  3.,  nan,   1.,   8.,  nan],
       [  4.,   9.,   6.,  nan,  nan]])

我现在想在数组 arr 中逐行_243181_的 nan 值 . 我的意思是用左边最近的有效值替换每个 nan 值 . 期望的结果如下所示:

array([[  5.,   5.,   5.,  7.,  2.],
       [  3.,   3.,   1.,  8.,  8.],
       [  4.,   9.,   6.,  6.,  6.]])

到目前为止已经尝试过了

我尝试过使用for循环:

for row_idx in range(arr.shape[0]):
    for col_idx in range(arr.shape[1]):
        if np.isnan(arr[row_idx][col_idx]):
            arr[row_idx][col_idx] = arr[row_idx][col_idx - 1]

我也尝试使用pandas数据帧作为中间步骤(因为pandas数据帧有一个非常简洁的内置前向填充方法):

import pandas as pd
df = pd.DataFrame(arr)
df.fillna(method='ffill', axis=1, inplace=True)
arr = df.as_matrix()

上述两种策略都会产生预期的结果,但我一直想知道:只使用numpy矢量化操作的策略不是最有效的策略吗?


摘要

是否有另一种更有效的方法来在numpy数组中使用'forward-fill' nan 值? (例如,通过使用numpy矢量化操作)


更新:解决方案比较

到目前为止,我已尝试计算所有解决方案 . 这是我的设置脚本:

import numba as nb
import numpy as np
import pandas as pd

def random_array():
    choices = [1, 2, 3, 4, 5, 6, 7, 8, 9, np.nan]
    out = np.random.choice(choices, size=(1000, 10))
    return out

def loops_fill(arr):
    out = arr.copy()
    for row_idx in range(out.shape[0]):
        for col_idx in range(1, out.shape[1]):
            if np.isnan(out[row_idx, col_idx]):
                out[row_idx, col_idx] = out[row_idx, col_idx - 1]
    return out

@nb.jit
def numba_loops_fill(arr):
    '''Numba decorator solution provided by shx2.'''
    out = arr.copy()
    for row_idx in range(out.shape[0]):
        for col_idx in range(1, out.shape[1]):
            if np.isnan(out[row_idx, col_idx]):
                out[row_idx, col_idx] = out[row_idx, col_idx - 1]
    return out

def pandas_fill(arr):
    df = pd.DataFrame(arr)
    df.fillna(method='ffill', axis=1, inplace=True)
    out = df.as_matrix()
    return out

def numpy_fill(arr):
    '''Solution provided by Divakar.'''
    mask = np.isnan(arr)
    idx = np.where(~mask,np.arange(mask.shape[1]),0)
    np.maximum.accumulate(idx,axis=1, out=idx)
    out = arr[np.arange(idx.shape[0])[:,None], idx]
    return out

然后是这个控制台输入:

%timeit -n 1000 loops_fill(random_array())
%timeit -n 1000 numba_loops_fill(random_array())
%timeit -n 1000 pandas_fill(random_array())
%timeit -n 1000 numpy_fill(random_array())

导致此控制台输出:

1000 loops, best of 3: 9.64 ms per loop
1000 loops, best of 3: 377 µs per loop
1000 loops, best of 3: 455 µs per loop
1000 loops, best of 3: 351 µs per loop

4 回答

  • 3

    这是一种方法 -

    mask = np.isnan(arr)
    idx = np.where(~mask,np.arange(mask.shape[1]),0)
    np.maximum.accumulate(idx,axis=1, out=idx)
    out = arr[np.arange(idx.shape[0])[:,None], idx]
    

    如果您不想创建另一个数组并只填充 arr 本身的NaN,请用此替换最后一步 -

    arr[mask] = arr[np.nonzero(mask)[0], idx[mask]]
    

    样本输入,输出 -

    In [179]: arr
    Out[179]: 
    array([[  5.,  nan,  nan,   7.,   2.,   6.,   5.],
           [  3.,  nan,   1.,   8.,  nan,   5.,  nan],
           [  4.,   9.,   6.,  nan,  nan,  nan,   7.]])
    
    In [180]: out
    Out[180]: 
    array([[ 5.,  5.,  5.,  7.,  2.,  6.,  5.],
           [ 3.,  3.,  1.,  8.,  8.,  5.,  5.],
           [ 4.,  9.,  6.,  6.,  6.,  6.,  7.]])
    
  • 26

    使用Numba . 这应该会带来显着的加速:

    import numba
    @numba.jit
    def loops_fill(arr):
        ...
    
  • 1

    对于那些对foward-filling之后领先 np.nan 问题感兴趣的人,以下作品:

    mask = np.isnan(arr)
    first_non_zero_idx = (~mask!=0).argmax(axis=1) #Get indices of first non-zero values
    arr = [ np.hstack([
                 [arr[i,first_nonzero]]*(first_nonzero), 
                 arr[i,first_nonzero:]])
                 for i, first_nonzero in enumerate(first_non_zero_idx) ]
    
  • 1

    对于那些来到这里寻找向后填充NaN值的人,我修改了the solution provided by Divakar above来做到这一点 . 诀窍是你必须使用除最大值之外的最小值来对反转阵列进行累加 .

    这是代码:

    # As provided in the answer by Divakar
    def ffill(arr):
        mask = np.isnan(arr)
        idx = np.where(~mask, np.arange(mask.shape[1]), 0)
        np.maximum.accumulate(idx, axis=1, out=idx)
        out = arr[np.arange(idx.shape[0])[:,None], idx]
        return out
    
    # My modification to do a backward-fill
    def bfill(arr):
        mask = np.isnan(arr)
        idx = np.where(~mask, np.arange(mask.shape[1]), mask.shape[0] + 1)
        idx = np.minimum.accumulate(idx[:, ::-1], axis=1)[:, ::-1]
        out = arr[np.arange(idx.shape[0])[:,None], idx]
        return out
    
    
    # Test both functions
    arr = np.array([[5, np.nan, np.nan, 7, 2],
                    [3, np.nan, 1, 8, np.nan],
                    [4, 9, 6, np.nan, np.nan]])
    print('Array:')
    print(arr)
    
    print('\nffill')
    print(ffill(arr))
    
    print('\nbfill')
    print(bfill(arr))
    

    输出:

    Array:
    [[ 5. nan nan  7.  2.]
     [ 3. nan  1.  8. nan]
     [ 4.  9.  6. nan nan]]
    
    ffill
    [[5. 5. 5. 7. 2.]
     [3. 3. 1. 8. 8.]
     [4. 9. 6. 6. 6.]]
    
    bfill
    [[ 5.  7.  7.  7.  2.]
     [ 3.  1.  1.  8. nan]
     [ 4.  9.  6. nan nan]]
    

相关问题