Cumsum在NaN重置

wor*_*ins 16 python numpy pandas cumsum

如果我有一个1或NaN的pandas.core.series.Series命名ts如下:

3382   NaN
3381   NaN
...
3369   NaN
3368   NaN
...
15     1
10   NaN
11     1
12     1
13     1
9    NaN
8    NaN
7    NaN
6    NaN
3    NaN
4      1
5      1
2    NaN
1    NaN
0    NaN
Run Code Online (Sandbox Code Playgroud)

我想计算这个系列的cumsum但它应该在NaN的位置重置(设置为零),如下所示:

3382   0
3381   0
...
3369   0
3368   0
...
15     1
10     0
11     1
12     2
13     3
9      0
8      0
7      0
6      0
3      0
4      1
5      2
2      0
1      0
0      0
Run Code Online (Sandbox Code Playgroud)

理想情况下,我想有一个矢量化解决方案!

我曾经在Matlab看到过类似的问题: 在NaN上重置Matlab cumsum?

但我不知道如何翻译这一行 d = diff([0 c(n)]);

emp*_*ice 10

您的Matlab代码的简单Numpy翻译是这样的:

import numpy as np

v = np.array([1., 1., 1., np.nan, 1., 1., 1., 1., np.nan, 1.])
n = np.isnan(v)
a = ~n
c = np.cumsum(a)
d = np.diff(np.concatenate(([0.], c[n])))
v[n] = -d
np.cumsum(v)
Run Code Online (Sandbox Code Playgroud)

执行此代码将返回结果array([ 1., 2., 3., 0., 1., 2., 3., 4., 0., 1.]).此解决方案仅与原始解决方案一样有效,但如果它不足以满足您的需求,它可能会帮助您提供更好的解决方案.

  • 如果将 `a = ~n` 更改为 `a = np.nan_to_num(v)`,它也适用于值为 1 以外的 v。 (2认同)

Phi*_*oud 9

这是一个稍微有点大熊猫的方式:

v = Series([1, 1, 1, nan, 1, 1, 1, 1, nan, 1], dtype=float)
n = v.isnull()
a = ~n
c = a.cumsum()
index = c[n].index  # need the index for reconstruction after the np.diff
d = Series(np.diff(np.hstack(([0.], c[n]))), index=index)
v[n] = -d
result = v.cumsum()
Run Code Online (Sandbox Code Playgroud)

请注意,其中任何一个都要求您pandas至少使用9da899b或更新.如果你不是那么你可以投射bool dtypeint64float64 dtype:

v = Series([1, 1, 1, nan, 1, 1, 1, 1, nan, 1], dtype=float)
n = v.isnull()
a = ~n
c = a.astype(float).cumsum()
index = c[n].index  # need the index for reconstruction after the np.diff
d = Series(np.diff(np.hstack(([0.], c[n]))), index=index)
v[n] = -d
result = v.cumsum()
Run Code Online (Sandbox Code Playgroud)


kad*_*dee 9

更多大熊猫的方式:

v = pd.Series([1., 3., 1., np.nan, 1., 1., 1., 1., np.nan, 1.])
cumsum = v.cumsum().fillna(method='pad')
reset = -cumsum[v.isnull()].diff().fillna(cumsum)
result = v.where(v.notnull(), reset).cumsum()
Run Code Online (Sandbox Code Playgroud)

与matlab代码相反,这也适用于不同于1的值.

  • 这是最好的答案。如果您想了解它是如何工作的,只需在末尾再添加一行:`print(pd.DataFrame({'v':v,'cum':cumsum,'reset':reset,'result':result} ))`,然后运行此代码。 (2认同)

小智 6

如果您可以接受类似的布尔系列b,请尝试

(b.cumsum() - b.cumsum().where(~b).fillna(method='pad').fillna(0)).astype(int)
Run Code Online (Sandbox Code Playgroud)

从系列开始ts,无论是b = (ts == 1)b = ~ts.isnull()