[英]how to count the number of times the if statement is true in excel sheet using pandas?
[英]How to count the number of times a continuous condition is true?
A
列的每一行都與上次COND
True時的A值進行比較,如果小於它,則滿足條件,並累加計數。 停止計數,直到大於或等於。
輸入:
import pandas as pd
A=[28,30,15,25,24,13,31,19,20,11,19,21]
COND=[False,True,False,False,False,False,False,False,True,False,False,False]
df=pd.DataFrame({'A':A,'COND':COND})
預計 Output
A COND expected
0 28 FALSE 0
1 30 TRUE 0
2 15 FALSE 1
3 25 FALSE 2
4 24 FALSE 3
5 13 FALSE 4
6 31 FALSE 0
7 19 FALSE 0
8 20 TRUE 0
9 11 FALSE 1
10 19 FALSE 2
11 21 FALSE 0
為了達到這個結果,您需要遍歷列表以確定輸出值。
首先分配一些基本變量:
expected = []
lastTrue = None
count = 0
這些將在整個循環中進行修改。 接下來,循環並測試每個條件。
循環遍歷數字:
for i in range(len(A)):
num = A[i]
測試條件是否為真; 如果是,保存數字並重置計數:
if COND[i]: # If True, save the number and reset count
lastTrue = num
count = 0
檢查是否已找到 True 值:
elif lastTrue is None: # If haven't found a True value yet, pass
pass
根據最后一個真實數字測試該數字以確定 output:
elif num < lastTrue: # If less than the last True value, increment count
count += 1
else: # If larger than or equal to, reset count
count = 0
lastTrue = None
將當前計數添加到列表中:
expected.append(count)
現在您需要做的就是添加列並打印 output。
最終代碼:
import pandas as pd
A=[28,30,15,25,24,13,31,19,20,11,19,21]
COND=[False,True,False,False,False,False,False,False,True,False,False,False]
expected = []
lastTrue = None
count = 0
for i in range(len(A)):
num = A[i]
if COND[i]: # If True, save the number and reset count
lastTrue = num
count = 0
elif lastTrue is None: # If haven't found a True value yet, pass
pass
elif num < lastTrue: # If less than the last True value, increment count
count += 1
else: # If larger than or equal to, reset count
count = 0
lastTrue = None
expected.append(count)
df=pd.DataFrame({'A':A,'COND':COND,'EXPECTED':expected})
print(df)
Output:
A COND EXPECTED
0 28 False 0
1 30 True 0
2 15 False 1
3 25 False 2
4 24 False 3
5 13 False 4
6 31 False 0
7 19 False 0
8 20 True 0
9 11 False 1
10 19 False 2
11 21 False 0
這是一個老問題,你已經有了答案。 但我想我從“在 Pandas 框架內”添加了一個答案(即避免對 dataframe 行進行顯式迭代)。
你可以試試:
df["Res"] = df.groupby(df["COND"].cumsum()).agg(
Res=("COND", "cumcount"), A_cummax=("A", "cummax")
).assign(
A_first=df["A"].where(df["COND"]).ffill().fillna(df["A"]),
Res=lambda df: df["Res"].where(df["A_cummax"] <= df["A_first"], 0)
)["Res"]
df["COND"].cumsum()
標識您要處理的組,因此對其進行分組是第一步。.agg()
添加兩列: (1) Res
build by .cumcount()
幾乎是您正在尋找的結果,但必須進行一些調整。 (2) 輔助列A_cummax
。A_first
來標識相應的。 第A
值。 dataframe 現在看起來像: Res A_cummax A_first 0 0 28 28.0 1 0 30 30.0 2 1 30 30.0 3 2 30 30.0 4 3 30 30.0 5 4 30 30.0 6 5 31 30.0 7 6 31 30.0 8 0 20 20.0 9 1 20 20.0 10 2 20 20.0 11 3 21 20.0
Res
進行調整:超過第一個A
值后的零點。您的示例的結果與預期的一樣:
A COND Res
0 28 False 0
1 30 True 0
2 15 False 1
3 25 False 2
4 24 False 3
5 13 False 4
6 31 False 0
7 19 False 0
8 20 True 0
9 11 False 1
10 19 False 2
11 21 False 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.