【发布时间】:2020-04-02 23:23:19
【问题描述】:
我在 pandas 中有一个值为 0 和 1 的列。我想分配超过 9 个连续 1 的组号。
示例:
假设我的列值为:[1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1]
我想要一个新列或将同一列更改为:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,0,0,0,3,3,3,3,3,3,3,3,3,3,3]
我已经到了可以用另一个数字(例如 2)替换所有连续的 1(计数大于 9)的程度。这是代码:
def f(col, threshold=9):
mask = col.groupby((col != col.shift()).cumsum()).transform('count').gt(threshold)
mask &= col.eq(1)
#print (mask)
col.update(col.loc[mask].replace(1,2))
return col
【问题讨论】:
-
为什么人们会做这么长的例子?
标签: python pandas events time-series