如何根据numpy数组中的一系列数字用缺失值替换'0'?

How to replace `0`s with missing values according to a series of numbers in a numpy array?

我有一个包含一系列 intsnumpy 数组。我想用系列中缺失的值填充 0s。

最初,我在 pandas 数据框的一列中有这些值,但为了简单起见,我决定 post 使用 numpy 数组代替问题。

>>> a = np.array([15, 25, 0, 45, 0, 0, 75, 85])
>>> a
>>> array([15, 25,  0, 45,  0,  0, 75, 85])

我希望输出为,

>>> array([15, 25,  35, 45,  55,  65, 75, 85])

我想在不使用循环的情况下解决这个问题,因为这会破坏使用 numpypandas 的目的,并且使用循环的代码会慢得多。

我不想用新值替换整个列,这会作为副作用更新 0s。

我只想根据系列用缺失值更新 0s。

pandas 这很简单。您可以使用 interpolate 应用线性插值(其默认插值方法是 linear):

a = np.array([15, 25, 0, 45, 0, 0, 75, 85])
s = pd.Series(a)
s.mask(s.eq(0)).interpolate()

0    15.0
1    25.0
2    35.0
3    45.0
4    55.0
5    65.0
6    75.0
7    85.0
dtype: float64