MJS*_*MJS 5 python vectorization dataframe pandas
我正在尝试创建一个列("consec"),它将在不使用循环的情况下在另一个("二进制")中保持连续值的运行计数.这就是期望的结果:
. binary consec
1 0 0
2 1 1
3 1 2
4 1 3
5 1 4
5 0 0
6 1 1
7 1 2
8 0 0
Run Code Online (Sandbox Code Playgroud)
但是,这......
df['consec'][df['binary']==1] = df['consec'].shift(1) + df['binary']
Run Code Online (Sandbox Code Playgroud)
导致这...
. binary consec
0 1 NaN
1 1 1
2 1 1
3 0 0
4 1 1
5 0 0
6 1 1
7 1 1
8 1 1
9 0 0
Run Code Online (Sandbox Code Playgroud)
我看到其他帖子使用分组或排序,但不幸的是,我看不出这对我有用.在此先感谢您的帮助.
DSM*_*DSM 13
您可以使用compare-cumsum-groupby模式(我真的需要编写文档),最后cumcount:
>>> df = pd.DataFrame({"binary": [0,1,1,1,0,0,1,1,0]})
>>> df["consec"] = df["binary"].groupby((df["binary"] == 0).cumsum()).cumcount()
>>> df
binary consec
0 0 0
1 1 1
2 1 2
3 1 3
4 0 0
5 0 0
6 1 1
7 1 2
8 0 0
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为首先我们得到我们想要重置计数器的位置:
>>> (df["binary"] == 0)
0 True
1 False
2 False
3 False
4 True
5 True
6 False
7 False
8 True
Name: binary, dtype: bool
Run Code Online (Sandbox Code Playgroud)
这些累积总和为我们提供了每个组的不同ID:
>>> (df["binary"] == 0).cumsum()
0 1
1 1
2 1
3 1
4 2
5 3
6 3
7 3
8 4
Name: binary, dtype: int64
Run Code Online (Sandbox Code Playgroud)
然后我们可以将其传递给groupby并用于cumcount在每个组中获得增加的索引.