示例问题
作为一个简单的例子,考虑如下定义的 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
值。我的意思是用左边最接近的有效值替换每个 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 数组中的 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
nan
,会发生什么?
NaN
不变。我会假设 OP 想要相同的行为以保持一致性。
nan
值。因此,当代码(在第一列中遇到 nan
时)引发异常或将 nan
留在原处时,我可以接受。
as_matrix()
:原来的 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]
如果您不想创建另一个数组而只是在 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.]])
更新:正如 Financial_physician 在评论中指出的那样,我最初提出的解决方案可以简单地与反转数组上的 ffill
交换,然后反转结果。没有相关的性能损失。根据 %timeit
,我的初始解决方案似乎快 2% 或 3%。我更新了下面的代码示例,但保留了我的初始文本。
对于那些来这里寻找 NaN 值的反向填充的人,我修改了 the solution provided by Divakar above 来做到这一点。诀窍是您必须使用除最大值之外的最小值对反转数组进行累加。
这是代码:
# ffill along axis 1, 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
# Simple solution for bfill provided by financial_physician in comment below
def bfill(arr):
return ffill(arr[:, ::-1])[:, ::-1]
# My outdated modification of Divakar's answer to do a backward-fill
def bfill_old(arr):
mask = np.isnan(arr)
idx = np.where(~mask, np.arange(mask.shape[1]), mask.shape[1] - 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]]
编辑:根据 MS_ 的评论更新
bfill
中的 idx = np.where(~mask, np.arange(mask.shape[1]), mask.shape[0] + 1)
应该是 idx = np.where(~mask, np.arange(mask.shape[1]), mask.shape[1] - 1)
O(n)
并且你做了两次所以不会翻转,使用前向填充,然后取消翻转,与使用原始数组的 bfill 方法一样快吗?
%%timeit
为您的解决方案和我的解决方案计时,只有一个微不足道但一致的差异,10.3 µs(您的解决方案)与 9.95 µs(我的解决方案)。我会相应地更新我的回复。
我喜欢 Divakar 关于纯 numpy 的回答。这是 n 维数组的通用函数:
def np_ffill(arr, axis):
idx_shape = tuple([slice(None)] + [np.newaxis] * (len(arr.shape) - axis - 1))
idx = np.where(~np.isnan(arr), np.arange(arr.shape[axis])[idx_shape], 0)
np.maximum.accumulate(idx, axis=axis, out=idx)
slc = [np.arange(k)[tuple([slice(None) if dim==i else np.newaxis
for dim in range(len(arr.shape))])]
for i, k in enumerate(arr.shape)]
slc[axis] = idx
return arr[tuple(slc)]
AFIK pandas 只能处理二维,尽管有多个索引来弥补它。实现这一点的唯一方法是展平 DataFrame,取消堆叠所需的级别,重新堆叠,最后重塑为原始数据。这种unstacking/restacking/reshapeing,涉及pandas排序,只是实现相同结果的不必要开销。
测试:
def random_array(shape):
choices = [1, 2, 3, 4, np.nan]
out = np.random.choice(choices, size=shape)
return out
ra = random_array((2, 4, 8))
print('arr')
print(ra)
print('\nffull')
print(np_ffill(ra, 1))
raise SystemExit
输出:
arr
[[[ 3. nan 4. 1. 4. 2. 2. 3.]
[ 2. nan 1. 3. nan 4. 4. 3.]
[ 3. 2. nan 4. nan nan 3. 4.]
[ 2. 2. 2. nan 1. 1. nan 2.]]
[[ 2. 3. 2. nan 3. 3. 3. 3.]
[ 3. 3. 1. 4. 1. 4. 1. nan]
[ 4. 2. nan 4. 4. 3. nan 4.]
[ 2. 4. 2. 1. 4. 1. 3. nan]]]
ffull
[[[ 3. nan 4. 1. 4. 2. 2. 3.]
[ 2. nan 1. 3. 4. 4. 4. 3.]
[ 3. 2. 1. 4. 4. 4. 3. 4.]
[ 2. 2. 2. 4. 1. 1. 3. 2.]]
[[ 2. 3. 2. nan 3. 3. 3. 3.]
[ 3. 3. 1. 4. 1. 4. 1. 3.]
[ 4. 2. 1. 4. 4. 3. 1. 4.]
[ 2. 4. 2. 1. 4. 1. 3. 4.]]]
使用 Numba。这应该会显着加快速度:
import numba
@numba.jit
def loops_fill(arr):
...
我喜欢 Divakar 的回答,但它不适用于行以 np.nan 开头的边缘情况,如下面的 arr
arr = np.array([[9, np.nan, 4, np.nan, 6, 6, 7, 2, 3, np.nan],
[ np.nan, 5, 5, 6, 5, 3, 2, 1, np.nan, 10]])
使用 Divakar 代码的输出将是:
[[ 9. 9. 4. 4. 6. 6. 7. 2. 3. 3.]
[nan 4. 5. 6. 5. 3. 2. 1. 1. 10.]]
Divakar的代码可以简化一点,简化版同时解决了这个问题:
arr[np.isnan(arr)] = arr[np.nonzero(np.isnan(arr))[0], np.nonzero(np.isnan(arr))[1]-1]
如果连续出现多个np.nan
(无论是开头还是中间),只需重复此操作几次即可。例如,如果数组有 5 个连续的 np.nan
,则以下代码将使用这些 np.nan
之前的数字“前向填充”所有这些:
for i in range(0, 5):
value[np.isnan(value)] = value[np.nonzero(np.isnan(value))[0], np.nonzero(np.isnan(value))[1]-1]
对于那些对前向填充后有前导 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) ]
bottleneck push function 是向前填充的好选择。它通常在 Xarray 之类的包中内部使用,它应该比其他替代品更快,并且该包还具有一组 benchmarks。
例子:
import numpy as np
from bottleneck import push
a = np.array(
[
[1, np.nan, 3],
[np.nan, 3, 2],
[2, np.nan, np.nan]
]
)
push(a, axis=0)
array([[ 1., nan, 3.],
[ 1., 3., 2.],
[ 2., 3., 2.]])
使用bottleneck模块,它带有pandas或numpy模块,因此无需单独安装。
下面的代码应该会给你想要的结果。
import bottleneck as bn
bn.push(arr,axis=1)
如果你愿意使用 Pandas/xarray: 让axis是你希望填充/填充的方向,如下所示,
xr.DataArray(arr).ffill(f'dim_{axis}').values
xr.DataArray(arr).bfill(f'dim_{axis}').values
更多信息:http://xarray.pydata.org/en/stable/generated/xarray.DataArray.ffill.html https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.ffill.html
一个班轮:
result = np.where(np.isnan(arr), 0, arr)
在一个强制浮动的函数中(我需要它,因为我有 dtype=object
)。
def fillna(arr):
arr = np.array(arr,dtype=float)
out = np.where(np.isnan(arr), 0, arr)
return out
arr = np.array([[5, np.nan, np.nan, 7, 2],
[3, np.nan, 1, 8, np.nan],
[4, 9, 6, np.nan, np.nan]])
result = fillna(arr)
print(result)
# result
# array([[5., 0., 0., 7., 2.],
# [3., 0., 1., 8., 0.],
# [4., 9., 6., 0., 0.]])
通过轴选择和“向后”支持对 RichieV generalized pure numpy solution 进行了小幅改进
def _np_fill_(arr, axis=-1, fill_dir='f'):
"""Base function for np_fill, np_ffill, np_bfill."""
if axis < 0:
axis = len(arr.shape) + axis
if fill_dir.lower() in ['b', 'backward']:
dir_change = tuple([*[slice(None)]*axis, slice(None, None, -1)])
return np_ffill(arr[dir_change])[dir_change]
elif fill_dir.lower() not in ['f', 'forward']:
raise KeyError(f"fill_dir must be one of: 'b', 'backward', 'f', 'forward'. Got: {fill_dir}")
idx_shape = tuple([slice(None)] + [np.newaxis] * (len(arr.shape) - axis - 1))
idx = np.where(~np.isnan(arr), np.arange(arr.shape[axis])[idx_shape], 0)
np.maximum.accumulate(idx, axis=axis, out=idx)
slc = [np.arange(k)[tuple([slice(None) if dim==i else np.newaxis
for dim in range(len(arr.shape))])]
for i, k in enumerate(arr.shape)]
slc[axis] = idx
return arr[tuple(slc)]
def np_fill(arr, axis=-1, fill_dir='f'):
"""General fill function which supports multiple filling steps. I.e.:
fill_dir=['f', 'b'] or fill_dir=['b', 'f']"""
if isinstance(fill_dir, (tuple, list, np.ndarray)):
for i in fill_dir:
arr = _np_fill_(arr, axis=axis, fill_dir=i)
else:
arr = _np_fill_(arr, axis=axis, fill_dir=fill_dir)
return arr
def np_ffill(arr, axis=-1):
return np_fill(arr, axis=axis, fill_dir='forward')
def np_bfill(arr, axis=-1):
return np_fill(arr, axis=axis, fill_dir='backward')
除非我错过了什么,否则解决方案不适用于任何示例:
arr = np.array([[ 3.],
[ 8.],
[np.nan],
[ 7.],
[np.nan],
[ 1.],
[np.nan],
[ 3.],
[ 8.],
[ 8.]])
print("A:::: \n", arr)
print("numpy_fill::: \n ", numpy_fill(arr))
print("loop_fill", loops_fill(arr))
A::::
[[ 3.]
[ 8.]
[nan]
[ 7.]
[nan]
[ 1.]
[nan]
[ 3.]
[ 8.]
[ 8.]]
numpy_fill:::
[[ 3.]
[ 8.]
[nan]
[ 7.]
[nan]
[ 1.]
[nan]
[ 3.]
[ 8.]
[ 8.]]
loop_fill [[ 3.]
[ 8.]
[nan]
[ 7.]
[nan]
[ 1.]
[nan]
[ 3.]
[ 8.]
[ 8.]]
Comments ??
不定期副业成功案例分享
numpy.array([0.83, 0.83, 0.83, 0.83, nan, nan, nan])
?mask.shape[1]
替换为mask.size
并删除axis=1
并将最后一行替换为out = arr[idx]
arr
替换为fillMatrix
。我的案例是降低时间序列数据的分辨率,所以我转发了最新的条目