【问题标题】:Count the number of times values change in a series计算一系列值变化的次数
【发布时间】:2023-03-20 01:32:01
【问题描述】:

考虑系列:

s = [1, -1, 1, 1, 1, -1]

计算此类序列中值更改次数的最省时方法是什么?在这个例子中,答案是 3(从 1 到 -1,回到 1,再到 -1)

【问题讨论】:

    标签: python python-3.x pandas


    【解决方案1】:

    我将使用numpy

    (np.diff(s)!=0).sum()
    Out[497]: 3
    

    【讨论】:

    • 如此简洁和完美。再次感谢
    【解决方案2】:

    使用numpy 的替代解决方案是

    np.count_nonzero(np.diff(s))
    

    原生 Python 解决方案是

    sum(s[i - 1] != s[i] for i in range(1, len(s)))
    

    【讨论】:

      【解决方案3】:

      我会继续这样做,如果错了,请纠正我..! :)

      # This will append 1 in list if change occurs
      c = [1 for i,x in enumerate(s[:-1]) if x!= s[i+1] ]  
      # Printing the length of list which is ultimately the total no. of change
      print(len(c))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-26
        • 2021-10-25
        • 2013-06-21
        • 2013-03-04
        • 1970-01-01
        • 2018-09-08
        • 2023-03-27
        • 1970-01-01
        相关资源
        最近更新 更多