Pandas data frame transform INT64 columns to boolean

Learn, how to transform int64 columns to Boolean? By Pranit Sharma Last updated : October 06, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Problem statement

Suppose we are given with Pandas dataframe with multiple columns, out of which some column is stored as datatype int64 the values of this column are 1 or 0.

Transforming INT64 columns to boolean

We need to find a way to replace these values with Boolean values. In programming, we sometimes use some specific values that only have two values, either True or False. These values are known as Boolean values.

For this purpose, we will simply change the data type of that particular column to the 'bool' data type.

Let us understand with the help of an example,

Python program for pandas data frame transform INT64 columns to boolean

# Importing pandas
import pandas as pd

# Import numpy
import numpy as np

# Creating a dataframe
df = pd.DataFrame(np.random.random_integers(0,1,size=5), columns=['A'])

# Display original DataFrame
print("Original DataFrame:\n",df,"\n")

# Show current data type
print("Datatypes:\n",df.dtypes,"\n")

# Converting dtype of A
df['A'] = df['A'].astype('bool')

# Display new df and dtypes
print("New DataFrame:\n",df,"\n","New Dtypes","\n",df.dtypes)

Output:

Example: Pandas data frame transform INT64 columns to boolean

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.