美文网首页
pandas如何找到连续/不连续的0

pandas如何找到连续/不连续的0

作者: 井底蛙蛙呱呱呱 | 来源:发表于2020-04-02 11:39 被阅读0次
import pandas as pd

df = pd.DataFrame({
    'names': ['A','B','C','D','E','F','G','H','I','J','K','L'],
    'col1': [0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0],
    'col2': [0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0]})

names   col1    col2
A   0   0
B   1   0
C   0   0
D   1   0
E   1   1
F   1   0
G   0   1
H   0   0
I   0   1
J   1   0
K   0   0
L   0   0


def f(col, threshold=3):
    mask = col.groupby((col != col.shift()).cumsum()).transform('count').lt(threshold)
    mask &= col.eq(0)
    col.update(col.loc[mask].replace(0,1))
    return col

In [79]: df.apply(f, threshold=3)
Out[79]:
       col1  col2
names
A         1     0
B         1     0
C         1     0
D         1     0
E         1     1
F         1     1
G         0     1
H         0     1
I         0     1
J         1     0
K         1     0
L         1     0

step by step

In [84]: col = df['col2']

In [85]: col
Out[85]:
names
A    0
B    0
C    0
D    0
E    1
F    0
G    1
H    0
I    1
J    0
K    0
L    0
Name: col2, dtype: int64

In [86]: (col != col.shift()).cumsum()
Out[86]:
names
A    1
B    1
C    1
D    1
E    2
F    3
G    4
H    5
I    6
J    7
K    7
L    7
Name: col2, dtype: int32

In [87]: col.groupby((col != col.shift()).cumsum()).transform('count')
Out[87]:
names
A    4
B    4
C    4
D    4
E    1
F    1
G    1
H    1
I    1
J    3
K    3
L    3
Name: col2, dtype: int64

In [88]: col.groupby((col != col.shift()).cumsum()).transform('count').lt(3)
Out[88]:
names
A    False
B    False
C    False
D    False
E     True
F     True
G     True
H     True
I     True
J    False
K    False
L    False
Name: col2, dtype: bool

In [89]: col.groupby((col != col.shift()).cumsum()).transform('count').lt(3) & col.eq(0)
Out[89]:
names
A    False
B    False
C    False
D    False
E    False
F     True
G    False
H     True
I    False
J    False
K    False
L    False
Name: col2, dtype: bool

reference: https://datascience.stackexchange.com/questions/20587/find-the-consecutive-zeros-in-a-dataframe-and-do-a-conditional-replacement

相关文章

  • pandas如何找到连续/不连续的0

    step by step reference: https://datascience.stackexchange...

  • Pandas数据操作

    Pandas数据操作 Series索引 行索引 切片索引 不连续索引 布尔索引 DataFrame索引 列索引 不...

  • 不连续

    不连续 好好回想

  • 可导、连续、可微

    连续 连续的定义是什么? limf(x,y)=f(x0,y0),则称函数在(x0,y0)连续; 连续的物理意义是什...

  • 跨越不连续

    1.对于一个快速增长的公司,他必须具备 *提供的产品或服务是大多数人想要的 *提供的产品或服务能同时覆盖他们 2....

  • Pandas 重新排列行索引

    pandas dataframe 去重或者去除某些行数据后导致行索引 index 不连续,重新排列行索引 index:

  • 王煜全讲创新

    时代级别的创新需要找到社会发展的3个不连续性: 1.社会变革产生的不连续性,比如战争和改朝换代 2.人群的不连续性...

  • 不连续的世界

    小时候,在台州。从城西到城东,骑辆自行车,也不过20分钟的光景。那时候,如果是骑车,我喜欢看路旁一间接一间的店铺:...

  • 如何看待 “不连续性”

    记得李善友老师曾经在得到里有一期说到过一个概念—— “不连续性”。我今天就想结合自身谈谈我自己的理解。 “不连续性...

  • 《如何面对不连续之未来?》

    大部分人可能从来没有总结梳理过自己的知识和经验,但往往在实际做事情的过程中都遵循一套科学的方法和逻辑。 在现实生活...

网友评论

      本文标题:pandas如何找到连续/不连续的0

      本文链接:https://www.haomeiwen.com/subject/isztphtx.html