Convert Integer Column to Boolean Data Type in pandas DataFrame in Python (3 Examples)
This tutorial explains how to convert an integer column to the boolean data type in a pandas DataFrame in Python programming.
Setting up the Examples
import pandas as pd # Import pandas library in Python |
import pandas as pd # Import pandas library in Python
df = pd.DataFrame({'A':[1, 1, 0, 1, 0], # Constructing a pandas DataFrame 'B':[0, 1, 1, 0, 1], 'C':[1, 1, 1, 1, 0]}) print(df) # A B C # 0 1 0 1 # 1 1 1 1 # 2 0 1 1 # 3 1 0 1 # 4 0 1 0 |
df = pd.DataFrame({'A':[1, 1, 0, 1, 0], # Constructing a pandas DataFrame 'B':[0, 1, 1, 0, 1], 'C':[1, 1, 1, 1, 0]}) print(df) # A B C # 0 1 0 1 # 1 1 1 1 # 2 0 1 1 # 3 1 0 1 # 4 0 1 0
print(df.dtypes) # Printing the data types of all columns # A int64 # B int64 # C int64 # dtype: object |
print(df.dtypes) # Printing the data types of all columns # A int64 # B int64 # C int64 # dtype: object
Example 1: Transforming One Column of a pandas DataFrame from Integer to Boolean
df1 = df.copy() # Duplicate pandas DataFrame df1['A'] = df1['A'].astype(bool) # Converting integer to boolean |
df1 = df.copy() # Duplicate pandas DataFrame df1['A'] = df1['A'].astype(bool) # Converting integer to boolean
print(df1.dtypes) # Printing the data types of all columns # A bool # B int64 # C int64 # dtype: object |
print(df1.dtypes) # Printing the data types of all columns # A bool # B int64 # C int64 # dtype: object
Example 2: Transforming Multiple Columns of a pandas DataFrame from Integer to Boolean
df2 = df.copy() # Duplicate pandas DataFrame df2 = df2.astype({'A': bool, 'C': bool}) # Converting integer to boolean |
df2 = df.copy() # Duplicate pandas DataFrame df2 = df2.astype({'A': bool, 'C': bool}) # Converting integer to boolean
print(df2.dtypes) # Printing the data types of all columns # A bool # B int64 # C bool # dtype: object |
print(df2.dtypes) # Printing the data types of all columns # A bool # B int64 # C bool # dtype: object
Example 3: Transforming Each Column of a pandas DataFrame from Integer to Boolean
df3 = df.copy() # Duplicate pandas DataFrame df3 = df3.astype(bool) # Converting integer to boolean |
df3 = df.copy() # Duplicate pandas DataFrame df3 = df3.astype(bool) # Converting integer to boolean
print(df3.dtypes) # Printing the data types of all columns # A bool # B bool # C bool # dtype: object |
print(df3.dtypes) # Printing the data types of all columns # A bool # B bool # C bool # dtype: object
Related Articles
You may find some related Python tutorials on topics such as naming data, counting, and groups below:
- Identify Column Indices in pandas DataFrame in Python in R
- Count Distinct Values by Group of pandas DataFrame Column in Python
- Test whether Column Name Exists in pandas DataFrame in Python
- Calculate Column & Row Sums of pandas DataFrame in Python
- Order Rows of pandas DataFrame by Column in Python
- Get Column & Row Means of pandas DataFrame in Python