python - 递增数组/系列中的连续正组

标签 python pandas numpy series

假设我有一个像这样的 bool 值系列。

vals = pd.Series([0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1]).astype(bool)

>>> vals
0     False
1     False
2     False
3      True
4      True
5      True
6      True
7     False
8     False
9      True
10     True
11    False
12     True
13     True
14     True
dtype: bool

我想把这个 bool 系列变成一个系列,其中每组 1 都被正确枚举,就像这样

0     0
1     0
2     0
3     1
4     1
5     1
6     1
7     0
8     0
9     2
10    2
11    0
12    3
13    3
14    3

我怎样才能有效地做到这一点


我已经能够手动执行此操作,在 Python 级别循环遍历该系列并递增,但这显然很慢。我正在寻找矢量化解决方案 - 我看到了 this answer from unutbu关于在 NumPy 中拆分增加的组,并试图让它与某种类型的 cumsum 一起工作,但到目前为止还没有成功。

最佳答案

你可以试试这个:

vals.astype(int).diff().fillna(vals.iloc[0]).eq(1).cumsum().where(vals, 0)

#0     0
#1     0
#2     0
#3     1
#4     1
#5     1
#6     1
#7     0
#8     0
#9     2
#10    2
#11    0
#12    3
#13    3
#14    3
#dtype: int64

关于python - 递增数组/系列中的连续正组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46206214/

相关文章:

python - 使用 Python 在 3D 无噪声标量场中寻找峰值

Python Django Queryset 仅从日期获取月份和年份

Python/Pandas/spacy - 遍历 DataFrame 并计算 pos_ 标签的数量

python - 删除 Pandas Dataframe 中的列 : Inconsistency in Output

python - 寻找函数的最大值

python - Tensorflow:如何像在 numpy 中一样使用 2D 索引对张量进行索引

python - 使用 Tkinter 绘制矩形?

python - 删除所有非字母字符并分成新列

python - 从 Python 中执行不同 where 子句的 SQL

python - 如何使用日期索引和多级列进行切片 (MultiIndex)