Harish reddy
Harish reddy

Reputation: 431

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

Upvotes: 0

Views: 72

Answers (2)

Erfan
Erfan

Reputation: 42946

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

Upvotes: 1

Chris
Chris

Reputation: 338

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

Upvotes: 1

Related Questions