当第三列更改时,我如何在列中创建两个计数器?例如,我有下面的Flag,我想在一列中开始计数,然后在Flag更改时将其值更改为nan,并在另一列中计数,并以这种方式继续来回计数。
Flag Counter1 Counter2
0 1 nan
0 1 nan
0 1 nan
1 nan 1
1 nan 1
1 nan 1
0 2 nan
1 nan 2
答案 0 :(得分:1)
您可以使用:
#create consecutives groups
a = df['Flag'].ne(df['Flag'].shift()).cumsum()
m1 = df['Flag'] == 1
m2 = df['Flag'] == 0
#get Trues for edge rows
m3 = ~a.duplicated()
m4 = m3 & m1
m5 = m3 & m2
#add NaNs or count by cumulative sum
df['Counter2'] = np.where(m2, np.nan, m4.cumsum())
df['Counter1'] = np.where(m1, np.nan, m5.cumsum())
print (df)
Flag Counter1 Counter2
0 0 1.0 NaN
1 0 1.0 NaN
2 0 1.0 NaN
3 1 NaN 1.0
4 1 NaN 1.0
5 1 NaN 1.0
6 0 2.0 NaN
7 1 NaN 2.0