[英]how to subtract previous row value from current row value based on condition in pandas DataFrame?
[英]Multiple IF condition based on previous and the current row - Pandas
我想創建一個新列G
,如果D
列的前一行包含chrg
或float
並且當前行包含Dischrg
,則該列應顯示1
。 第一行應包含0
。
我想要與以下 excel 代碼等效的 pandas 代碼:
=IF(AND(D2="Chrg",D3="Dischrg"),G2+1,IF(AND(D2="Float",D3="Dischrg"),G2+1,0))
D G
Chrg 0
Dischrg 1
Float 0
Dischrg 0
Float 0
Dischrg 1
您可以移動列,以便在同一行中具有先前的值:
In [1]: import pandas as pd
In [2]: df = pd.DataFrame([{"a": 1, "b": 1}, {"a": 2, "b": 2}, {"a": 3, "b": 3}])
In [3]: df
Out[3]:
a b
0 1 1
1 2 2
2 3 3
In [4]: df["prev"] = df.a.shift(1)
In [5]: df
Out[5]:
a b prev
0 1 1 NaN
1 2 2 1.0
2 3 3 2.0
將Series.shift
與Series.isin
一起使用:
m1 = df['D'].shift().isin(['Chrg', 'Float']) # Chrg or Float previous row
m2 = df['D'].eq('Dischrg') # Current row Dischrg
df['G'] = (m1&m2).astype(int)
D G
0 Chrg 0
1 Dischrg 1
2 Float 0
3 Dischrg 1
4 Float 0
5 Dischrg 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.