Convert Integer Column To Boolean And Boolean To Integer in Pandas Dataframe

There are some small but important things that we keep on doing on a daily basis and then keep on forgetting. Here’s another one:

Convert Integer To Boolean And Boolean To Integer Values in Pandas Dataframe

So, Let’s keep it simple and direct to the solution:

Steps:

1. Import Pandas
2. Load Data as a Pandas Dataframe
3. Convert an Integer column to Boolean Values
4. Convert a Boolean Column to Integer

-> Import Pandas
# Import pandas package 
import pandas as pd

-> Load Data as Pandas Dataframe 

# Load Data 
df_data = pd.read_csv("Titanic_Original.csv")
df_data.info()

The “Survived” column seems to be the perfect candidate for this post. It is an Integer Column with two values 0 and 1. 

> Convert an Integer column to Boolean Values
Let’s convert “Survived” column to a Boolean variable.

# Convert "Survived" column to Boolean
df_data.Survived = df_data.Survived.astype('bool')
df_data.dtypes

That’s it! Let’s check the data type now.


-> Convert Boolean to Integer

Now, let’s convert “Survived” column back to Integer. 

# Convert "Survived" column to Integer
df_data.Survived = df_data.Survived.astype('int') 
df_data.dtypes

And that’s all! There are some other ways to convert from boolean to Integer like using map() function or numpy library. But this one works too!

2

Leave a Reply

Your email address will not be published. Required fields are marked *