简体   繁体   中英

Multiple IF condition based on previous and the current row - Pandas

I want to create a new column G which should display 1 if the previous row of D column contains a chrg or float and the current rows contains Dischrg . The first row should contain 0 .

I want the pandas equivalent of the following excel code:

=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

You can shift the column so you have the previous value in the same row:

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

Use Series.shift with 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM