# Write a Python code to convert a given series into a dummy variable and drop any NaN values if they exist

PythonPandasServer Side ProgrammingProgramming

Assume, you have a series and the result for converting to dummy variable as,

   Female Male
0    0    1
1    1    0
2    0    1
3    1    0
4    0    1
5    0    0
6    1    0
7    1    0

To solve this, we will follow the steps given below −

## Solution

• Create a list with ‘Male’ and ‘Female’ elements and assign into Series.

• Apply get_dummies function inside series and set dummy_na value as False. It is defined below,

pd.get_dummies(series, dummy_na=False)

### Example

Let’s check the following code to get a better understanding −

import pandas as pd
import numpy as np
gender = ['Male','Female','Male','Female','Male',np.nan,'Female','Female',]
series = pd.Series(gender)
print("Series is:\n",series)
print("Dummy code is:\n", pd.get_dummies(series, dummy_na=False))

### Output

Series is:
0    Male
1    Female
2    Male
3    Female
4    Male
5    NaN
6    Female
7    Female
dtype: object
Dummy code is:
Female Male
0    0    1
1    1    0
2    0    1
3    1    0
4    0    1
5    0    0
6    1    0
7    1    0
Published on 12-Feb-2021 11:14:22