- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Write a Python code to convert a given series into a dummy variable and drop any NaN values if they exist
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
- Related Articles
- Write a Python code to combine two given series and convert it to a dataframe
- Write a Python code to create a series with your range values, generate a new row as sum of all the values and then convert the series into json file
- Write a Python code to concatenate two Pandas series into a single series without repeating the index
- Write a program in Python to find the index for NaN value in a given series
- Write a Python code to select any one random row from a given DataFrame
- Write a Python code to fill all the missing values in a given dataframe
- Python Pandas - Drop the value when any level is NaN in a Multi-index
- How to create a dummy variable in R?
- How to check if a variable is NaN in JavaScript?
- Write a Python code to rename the given axis in a dataframe
- Write a Python code to filter palindrome names in a given dataframe
- Write a Python program to separate a series of alphabets and digits and convert them to a dataframe
- Program to convert gray code for a given number in python
- Write a program in Python to print numeric index array with sorted distinct values in a given series
- How to replace NaN values by Zeroes in a column of a Pandas Series?

Advertisements