numpy数组中的向后计数

Mar*_*lli 4 python numpy pandas

假设我有一系列这样的整数值排列在一个numpy数组中。

nan = np.nan
arr = np.array([3, nan, nan, nan, 5, nan, nan, nan, nan, nan])
Run Code Online (Sandbox Code Playgroud)

nan 值应填充从第一个非空值到零的倒数。

[3, 2, 1, 0, 5, 4, 3, 2, 1, 0]
Run Code Online (Sandbox Code Playgroud)

cs9*_*s95 7

IMO,最简单的熊猫方法是groupbycumcount一起使用ascending=False

s = pd.Series(np.cumsum(~np.isnan(arr)))
s.groupby(s).cumcount(ascending=False)

0    3
1    2
2    1
3    0
4    5
5    4
6    3
7    2
8    1
9    0
dtype: int64
Run Code Online (Sandbox Code Playgroud)