How to use Pandas to convert float to int in Python [5 Methods]

Do you want to convert float to integer using Pandas? In this Python tutorial, I will explain how to use Pandas to convert float to int in Python using different methods with some illustrative examples.

To convert float to int in Pandas in Python, utilize df.astype() for straightforward truncation, round() combined with astype() for rounding values, df.apply() with a custom function for greater control, numpy.floor() or numpy.ceil() for floor or ceiling operations, and df.to_numeric() for handling strings or mixed data types before conversion.

Pandas to convert float to int in Python

There are five different methods in Pandas to convert float to int in Python:

  1. Using df.astype()
  2. Using round() with astype()
  3. Using df.apply()
  4. Using numpy.floor() or numpy.ceil()
  5. Using df.to_numeric()

Let’s see them one by one using some demonstrative examples:

1. Convert float to int Pandas using df.astype() function

Using the df.astype() function in Pandas to convert float to int in Python, directly changes the data type of a column to the integer, truncating all decimal parts.

Here is an example:

import pandas as pd

df = pd.DataFrame({'JFK Airport': [200.7, 195.5], 'LAX Airport': [180.2, 175.8]})
print("Before Converting:\n", df)
df = df.astype(int)
print("DataFrame after using df.astype():\n", df)

Output:

Before Converting:
    JFK Airport  LAX Airport
0        200.7        180.2
1        195.5        175.8
DataFrame after using df.astype():
    JFK Airport  LAX Airport
0          200          180
1          195          175

Below is a screenshot displaying the output following the implementation of the code in the Pycharm editor.

Pandas to convert float to int in Python

2. Pandas convert float to int using round() with astype() function

First, this method rounds the floating-point numbers to the nearest integer using Python’s round() function, then converts them to integers using astype(int). It’s useful when we want to round off values rather than simply truncating them.

READ:  Matplotlib Plot NumPy Array

Here is an example using the round() function with the astype() function in Python to convert float to int in Python:

import pandas as pd

df = pd.DataFrame({'Seattle': [3.76, 4.18], 'Miami': [5.34, 6.12]})
print("Before Converting:\n", df)
df = df.round().astype(int)
print("\nDataFrame using round() with astype():\n", df)

Output:

Before Converting:
    Seattle  Miami
0     3.76   5.34
1     4.18   6.12

DataFrame using round() with astype():
    Seattle  Miami
0        4      5
1        4      6

A screenshot is mentioned below, after implementing the code in the Pycharm editor.

how to convert float to int in pandas in Python

3. Pandas float to int using df.apply() function

This approach involves applying a custom function to each element of the DataFrame in Python. It allows for complex operations or conditions before converting floats to integers using the df.apply() function.

This is the code for Pandas to convert float to int in Python using df.apply() function:

import pandas as pd

def convert_to_int(x):
    return int(round(x))

df = pd.DataFrame({'California': [45.5, 48.3], 'Alaska': [20.1, 22.6]})
print("Before Converting:\n", df)
df['California'] = df['California'].apply(convert_to_int)
print("\nDataFrame using df.apply():\n", df)

Output:

Before Converting:
    California  Alaska
0        45.5    20.1
1        48.3    22.6

DataFrame using df.apply():
    California  Alaska
0          46    20.1
1          48    22.6

After executing the code in Pycharm, one can see the output in the below screenshot.

change float to int pandas in Python

4. float to int Pandas using np.floor() or np.ceil() function

These np.floor() or np.ceil() functions are used for the floor (rounding down) or ceiling (rounding up) operations before converting the values to integers in Python.

Here is the code, in Pandas to convert float to int in Python using np.floor() or np.ceil():

import pandas as pd
import numpy as np

df = pd.DataFrame({'Software Engineer': [105.7, 108.3], 'Teacher': [50.2, 51.5]})
print("Before Converting:\n", df)
df['floor_income'] = np.floor(df['Software Engineer']).astype(int)
df['ceil_income'] = np.ceil(df['Teacher']).astype(int)
print("\nDataFrame using numpy.floor() or numpy.ceil():\n", df)

Output:

Before Converting:
    Software Engineer  Teacher
0              105.7     50.2
1              108.3     51.5

DataFrame using numpy.floor() or numpy.ceil():
    Software Engineer  Teacher  floor_income  ceil_income
0              105.7     50.2           105           51
1              108.3     51.5           108           52

After implementing the code in the Pycharm editor, the screenshot is mentioned below.

convert float to int pandas in Python

5. Pandas change float to int using df.to_numeric() function

The df.to_numeric() method is ideal for converting strings or mixed-type columns to a numeric type before casting them into integers in Python.

READ:  PyTorch Reshape Tensor - Useful Tutorial

Here is the code in Pandas to convert float to int in Python using the df.to_numeric() function:

import pandas as pd

df = pd.DataFrame({'Northeast': ['25.5', '27.1'], 'Southwest': ['18.2', '19.4']})
print("Before Converting:\n", df)
df = df.apply(pd.to_numeric).astype(int)
print("\nDataFrame using df.to_numeric():\n", df)

Output:

Before Converting:
   Northeast Southwest
0      25.5      18.2
1      27.1      19.4

DataFrame using df.to_numeric():
    Northeast  Southwest
0         25         18
1         27         19

Below is a screenshot showcasing the output, captured after the code was executed in the Pycharm editor.

convert float to int python pandas

Conclusion

Here, I have explained five methods that can be used in Pandas to convert float to int in Python, showcasing the versatility and flexibility of the library. These methods include df.astype(), round() with astype(), df.apply(), numpy.floor() or numpy.ceil(), and df.to_numeric().

Each serves a unique purpose, ensuring we have the right tool for various data transformation scenarios.

You may also like to read: