Home > OS >  Adding flags on condition in python dataframes
Adding flags on condition in python dataframes

Time:12-14

Suppose I have a dataframe like this-

Class  Player_type  Goals  Assists
  A        forward    0       1
  A        defence    1       0
  A        defence    1       1
  B        forward    0       0
  B        defence    0       0 

I want to add a flag only if-
class = row 1 class and
Player_type = forward and
row 1 Player_type = defence and
row 1 assists = 0 and
goals = 0
Desired dataframe-

Class  Player_type  Goals  Assists  Flag  
  A        forward    0       1      1  
  A        defence    1       0      0  
  A        defence    1       1      0  
  B        forward    0       0      1  
  B        defence    0       0      0  

row 1 means data for the next row.

CodePudding user response:

Use:

# class = row 1 class
m1 = df['Class'].eq(df['Class'].shift(-1))
# Player_type = forward
m2 = df['Player_type'].eq('forward')
# row 1 Player_type = defence
m3 = df['Player_type'].shift(-1).eq('defence')
# row 1 assists = 0
m4 = df['Assists'].shift(-1).eq(0)
# goals = 0  
m5 = df['Goals'].eq(0)

df['Flag'] = (m1&m2&m3&m4&m5).astype(int)

NB. You can avoid shifting individual columns by using df2 = df2.shift(-1), then df2['Class'] in place of df['Class'].shift(-1), etc.

Output:

  Class Player_type  Goals  Assists  Flag
0     A     forward      0        1     1
1     A     defence      1        0     0
2     A     defence      1        1     0
3     B     forward      0        0     1
4     B     defence      0        0     0
  • Related