我想在 df 中为计数器创建一个新列,当温度值从零变为非零时,该计数器就会递增。
我正在附加用于逻辑的循环。该值位于计数器变量中,但我希望它位于下表中所示的列中。
prev_temp, counter, n= -300, 0,0
for index, row in df.iterrows():
if row.Tempo!=0 and prev_temp==0:
counter+=1
n+=1
prev_temp=rows.Tempo
elif row.Tempo==0 and prev_temp!= 0:
prev_temp=rows.Tempo
此表是预期的输出!^
最佳答案
使用带有 shift
和 cumsum
的 bool 值作为递增数。
s = df['Tempo '].shift().eq(0) & df['Tempo '].gt(0)
df['counter'] = s.cumsum() + 1
No. Tempo Count counter
0 1 80.0 1 1
1 2 81.6 1 1
2 3 0.0 1 1
3 4 0.0 1 1
4 5 0.0 1 1
5 6 81.6 2 2
6 7 80.0 2 2
7 8 83.7 2 2
8 9 0.0 2 2
9 10 0.0 2 2
10 11 0.0 2 2
11 12 81.6 3 3
print(s)
0 False
1 False
2 False
3 False
4 False
5 True # increment here.
6 False
7 False
8 False
9 False
10 False
11 True # increment here.
关于python - 在我的数据框中添加一个计数器列,该计数器列根据温度值(在其他列中)递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65765710/