Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ignore nan cells when performing a pandas lambda map

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

enter image description here

as you can see there are some nan values in the Day column.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading