【问题标题】:Streaks of True or False in pandas Series熊猫系列中的真假条纹
【发布时间】:2017-06-13 02:51:28
【问题描述】:

我正在尝试研究如何在熊猫系列中显示TrueFalse 的条纹。

数据:

p = pd.Series([True,False,True,True,True,True,False,False,True])

0     True
1    False
2     True
3     True
4     True
5     True
6    False
7    False
8     True
dtype: bool

我尝试了p.diff(),但不确定如何计算生成的False 值以显示我的期望输出,如下所示:。

0     0
1     0
2     0
3     1
4     2
5     3
6     0
7     1
8     0

【问题讨论】:

    标签: python pandas boolean series cumsum


    【解决方案1】:

    另一种替代解决方案是创建pSeries 的累积总和并减去最近的累积总和,其中p0。然后反转p 并做同样的事情。最后多个Series在一起:

    c = p.cumsum()
    a = c.sub(c.mask(p).ffill(), fill_value=0).sub(1).abs()
    c = (~p).cumsum()
    d = c.sub(c.mask(~(p)).ffill(), fill_value=0).sub(1).abs()
    
    print (a)
    0    0.0
    1    1.0
    2    0.0
    3    1.0
    4    2.0
    5    3.0
    6    1.0
    7    1.0
    8    0.0
    dtype: float64
    
    print (d)
    0    1.0
    1    0.0
    2    1.0
    3    1.0
    4    1.0
    5    1.0
    6    0.0
    7    1.0
    8    1.0
    dtype: float64
    
    print (a.mul(d).astype(int))
    0    0
    1    0
    2    0
    3    1
    4    2
    5    3
    6    0
    7    1
    8    0
    dtype: int32
    

    【讨论】:

      【解决方案2】:

      如果p 不等于shifted pcumsum,您可以使用通过比较创建的连续组的cumcount

      print (p.ne(p.shift()))
      0     True
      1     True
      2     True
      3    False
      4    False
      5    False
      6     True
      7    False
      8     True
      dtype: bool
      
      print (p.ne(p.shift()).cumsum())
      0    1
      1    2
      2    3
      3    3
      4    3
      5    3
      6    4
      7    4
      8    5
      dtype: int32
      
      print (p.groupby(p.ne(p.shift()).cumsum()).cumcount())
      0    0
      1    0
      2    0
      3    1
      4    2
      5    3
      6    0
      7    1
      8    0
      dtype: int64
      

      感谢MaxU 提供另一个解决方案:

      print (p.groupby(p.diff().cumsum()).cumcount())
      0    0
      1    0
      2    0
      3    1
      4    2
      5    3
      6    0
      7    1
      8    0
      dtype: int64 
      

      【讨论】:

        猜你喜欢
        • 2018-12-12
        • 1970-01-01
        • 2020-03-30
        • 2015-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多