Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the values of a column based on two conditions in Python

I have a dataset where I have the time in a game and the time of an event.

  EVENT     GAME
  0:34      0:43
  NaN       0:23
  2:34      3:43
  NaN       4:50

I want to replace the NaN in the EVENT column where GAME < 0.24 by the value in the GAME column.

 df['EVENT'][(df['GAME'] < '0:24') & (df['EVENT'] == 'NaN')] = df['GAME']

I have tried this but it dosen't work. Sorry if it is obvious. I am new to Python.

like image 350
Nico Coallier Avatar asked Apr 05 '17 13:04

Nico Coallier


1 Answers

You can use isnull for check NaN:

df.loc[(df['GAME'] < '0:24') & (df['EVENT'].isnull()), 'EVENT'] = df['GAME']
print (df)

  EVENT  GAME
0  0:34  0:43
1  0:23  0:23
2  2:34  3:43
3   NaN  4:50

Another solution with mask:

mask = (df['GAME'] < '0:24') & (df['EVENT'].isnull())
df['EVENT'] = df['EVENT'].mask(mask, df['GAME'])
print (df)
  EVENT  GAME
0  0:34  0:43
1  0:23  0:23
2  2:34  3:43
3   NaN  4:50

Or numpy.where:

df['EVENT'] = np.where(mask, df['GAME'], df['EVENT'])
print (df)
  EVENT  GAME
0  0:34  0:43
1  0:23  0:23
2  2:34  3:43
3   NaN  4:50
like image 54
jezrael Avatar answered Nov 14 '22 21:11

jezrael