在numpy数组中,最有效的方法是使用前向填充(forward-fill)来填充NaN值。
在numpy数组中,最有效的方法是使用前向填充(forward-fill)来填充NaN值。
示例问题
作为一个简单的例子,考虑如下定义的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
进行逐行的“向前填充”操作,即将每个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数组进行“向前填充”操作?(例如使用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): '''由shx2提供的Numba装饰器解决方案。''' 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): '''由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