I have the following dataframe and mapping dictionary:
df = pd.DataFrame({
'Name': ['Jim','Jack','Jim','Jack','Jim','Jack','Mick','Mick'],
'Day':['Mon','Tue','Mon',np.nan,'Sat','Sun','Tue',np.nan],
'Value':[10,20,30,40,50,60,70,80],
})
values = {
'Mon':['Monday','M']
,'Tue':['Tuesday','T']
,'Wed':['Wednesday','W']
,'Thu':['Thursday','TH']
,'Fri':['Friday','F']
,'Sat':['Saturday','SA']
,'Sun':['Sunday','SU']
}
df
as you can see there are some nan values in the Day column.
I am trying to add the following column:
df['Day_Name'] = 'The name of the person is ' + df['Name'] + ' and the day of the week is ' + df['Day'].map(lambda x: values[x][0])
but i am getting a nan error due to the 2 nan cells present. Is there anything i can skip over the blank cells (and return blank) for those particular rows in the new df['Day_Name'] column? Thanks!
>Solution :
Use dict.get with specify list with empty space for possible after selection first value get empty value:
s = df['Day'].map(lambda x: values.get(x, [''])[0])
df['Day_Name'] = 'The name of the person is ' + df['Name'] + ' and the day of the week is ' + s
print (df)
Name Day Value Day_Name
0 Jim Mon 10 The name of the person is Jim and the day of t...
1 Jack Tue 20 The name of the person is Jack and the day of ...
2 Jim Mon 30 The name of the person is Jim and the day of t...
3 Jack NaN 40 The name of the person is Jack and the day of ...
4 Jim Sat 50 The name of the person is Jim and the day of t...
5 Jack Sun 60 The name of the person is Jack and the day of ...
6 Mick Tue 70 The name of the person is Mick and the day of ...
7 Mick NaN 80 The name of the person is Mick and the day of ...
