Convert Float Column to Integer Data Type in pandas DataFrame in Python (3 Examples)

In this Python tutorial you’ll learn how to transform a float column to the integer data type in a pandas DataFrame.

Preparing the Examples

import pandas as pd                           # Import pandas library to Python
df = pd.DataFrame({'A':[4.1, 9, 12, 1, 7],    # Constructing a pandas DataFrame
                   'B':[10.1, 9, 77, 22, 24],
                   'C':[35.1, 41, 41, 1, 13]})
print(df)
#       A     B     C
# 0   4.1  10.1  35.1
# 1   9.0   9.0  41.0
# 2  12.0  77.0  41.0
# 3   1.0  22.0   1.0
# 4   7.0  24.0  13.0
print(df.dtypes)                              # Printing the data types of all columns
# A    float64
# B    float64
# C    float64
# dtype: object

Example 1: Transforming One Column of a pandas DataFrame from Float to Integer

df1 = df.copy()                               # Duplicate pandas DataFrame
df1['A'] = df1['A'].astype(int)               # Converting float to integer
print(df1.dtypes)                             # Printing the data types of all columns
# A      int32
# B    float64
# C    float64
# dtype: object

Example 2: Transforming Multiple Columns of a pandas DataFrame from Float to Integer

df2 = df.copy()                               # Duplicate pandas DataFrame
df2 = df2.astype({'A': int, 'C': int})        # Converting float to integer
print(df2.dtypes)                             # Printing the data types of all columns
# A      int32
# B    float64
# C      int32
# dtype: object

Example 3: Transforming Each Column of a pandas DataFrame from Float to Integer

df3 = df.copy()                               # Duplicate pandas DataFrame
df3 = df3.astype(int)                         # Converting float to integer
print(df3.dtypes)                             # Printing the data types of all columns
# A    int32
# B    int32
# C    int32
# dtype: object

Further Resources & Related Articles

Below, you may find some further resources on topics such as groups and counting:

Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top