根据条件,计数器集或具有相同编号的行

时间:2019-04-13 00:55:13

标签: python counter

我有数据集。对于特定条件,有一列具有True或False值。如果存在具有相同值的行序列,则让这些行的计数器相同。

为了清楚起见,下面是我的代码:

c1 = [True,True,False,False,False,True,False,True,True,False,True]
counter = 1
switch = 0 #increase the counter when the vector has switched twice
c2 = np.repeat(None, len(c1))
c2[i]=counter

for i in range(1,len(c1)):
    p = c1[i-1]
    x = c1[i]
    if p==x:
        counter=counter
        c2[i]=counter


    if p!=x : 
        switch = switch + 1

        c2[i]=switch



    elif switch == 2: 
            counter = counter + 1  

            switch = 0 #reset the counter


print(c2) 

实际输出是

[None 1 1 1 1 2 3 4 1 5 6] 

而预期的应该是

[None, 1,1,1,1,2,2,3,3,3,4]

1 个答案:

答案 0 :(得分:0)

 c1 = [True,True,False,False,False,True,False,True,True,False,True]
 res = []
 var = 1

 cur=c1[0]
 flag = 0
 res.append(None)

 for val in c1[1:]:
     if val==cur and flag == 0:
         res.append(var)
     elif val == cur and flag == 1:
         var+=1
         flag = 0
         res.append(var)
     elif val != cur and flag == 0:
         flag = 1
         res.append(var)
     elif val != cur and flag == 1:
         res.append(var)
     else:
         pass

 print(res)

输出:[无,1、1、1、1、2、2、3、3、3、4]