簡體   English   中英

如何在 python 的 for 循環期間計算值變化?

[英]How to count value change during a for loop in python?

我有一個 dataframe 由一列組成,該列由01組成。

它們以這種方式構造[0,0,1,1,0,0,1,1,1,]

我的目標是只計算循環中每個重復1秒中的第一個1

所以在這個[0,0,1,1,0,0,1,1,1,]的例子中,它應該只能計算總數2 如何使用 for 循環並使用if條件並計算它?

(正如@Erfan 在評論中提到的那樣:)

>>> df
   col
0    0
1    0
2    1
3    1
4    0
5    0
6    1
7    1
8    1

>>> df['col'].diff().eq(1).sum()
2

找到了一種混亂的方法,我可以創建一個翻譯列表並計算總和。

def FirstValue(data):      
for index, item in enumerate(data):    
    if item == 1:
        if data[index-1] == 1:
            counter.append(0)            
    if item == 1:
        if data[index-1] == 0:
            counter.append(1)            
    else:
        counter.append(0)

一個簡單的for循環:

out = [0]+[int(j-i==1) for i,j in zip(lst,lst[1:])]

Output:

[0, 0, 1, 0, 0, 0, 1, 0, 0]

此外,您可以將pd.Series分配給 DataFrame 列,例如:

df.col = (pd.Series(lst).diff()==1).astype(int)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM