gpt4 book ai didi

python - 列变化计数器

转载 作者:太空宇宙 更新时间:2023-11-03 14:14:17 25 4
gpt4 key购买 nike

当第三列发生变化时,我将如何在列中创建两个计数器?例如,我有下面的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

最佳答案

您可以使用:

#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

关于python - 列变化计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48307163/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com