计算值在系列中更改的次数

时间:2019-06-08 20:02:59

标签: python python-3.x pandas

考虑系列:

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

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

3 个答案:

答案 0 :(得分:2)

我将使用<img id="gemStoneAll" onclick="ChangeLayout('all')" /> <img id="gemStoneUncommon" onclick="ChangeLayout('uncommon')" /> <img id="gemStoneRare" onclick="ChangeLayout('rare')" /> <img id="gemStoneVeryRare" onclick="ChangeLayout('veryrare')" /> <ul id=catalogGrid> <li> <div class="itemContainer rare"> </div> </li> <li> <div class="itemContainer veryrare"> </div> </li> <li> <div class="itemContainer uncommon"> </div> </li> <li> <div class="itemContainer uncommon"> </div> </li> <li> <div class="itemContainer rare"> </div> </li> <li> <div class="itemContainer rare"> </div> </li> </ul>

numpy

答案 1 :(得分:2)

使用numpy的替代解决方案是

np.count_nonzero(np.diff(s))

原生Python解决方案是

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

答案 2 :(得分:1)

我会继续这样做,如果有错,请纠正我。 :)

# 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))

enter image description here