Dataframe replace string with a word and set other rows as NULL using Python pandas

Viewed 52

I have a dataframe in python, want to replace Fri as this friday and the rest of the rows in that colume as NULL enter image description here

Use this code will replace all the rows with this friday, which is not what i want

import datetime
today = datetime.date.today()
friday = today + datetime.timedelta( (4-today.weekday()) % 7 )
this_firday = friday.strftime('%Y-%m-%d')

df['date3'] = df.loc[(df['date'] == 'Fri'), 'date'] = this_firday 
df

my expected result is

enter image description here

1 Answers

try via map():

df['date']=df['date'].map({'Fri':this_firday})

OR

via loc:

df.loc[(df['date'] == 'Fri'), 'date'] = this_firday
df.loc[(df['date'] != 'Fri'),'date']=float('NaN')

OR

you can also use np.where():

#import numpy as np
df['date']=np.where((df['date'] == 'Fri'),this_firday,np.nan)
Related