W3docs

Convert floats to ints in Pandas?

To convert floats to integers in Pandas, you can use the astype() function.

To convert floats to integers in Pandas, you can use the astype() function. This function allows you to convert a column or series of a DataFrame to a different data type.

For example, suppose you have a DataFrame df with a column 'col' that contains floating point values:

Convert floats to ints in Pandas library of Python

import pandas as pd

df = pd.DataFrame({'col': [1.5, 2.6, 3.7, 4.8]})
print(df)

# Output:
#    col
# 0  1.5
# 1  2.6
# 2  3.7
# 3  4.8

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

To convert the values in this column to integers, you can use the following code:

Convert floats to ints in Pandas library of Python using the astype method

df['col'] = df['col'].astype(int)
print(df)

# Output:
#    col
# 0    1
# 1    2
# 2    3
# 3    4

Note that when converting float values to integers, the decimal part of the float will be truncated (not rounded). For example, the value 1.5 will be converted to 1, and the value 2.6 will be converted to 2.

You can also use the astype() function to convert multiple columns at once. For example:

Convert floats to ints in Pandas library of Python using the astype method on multiple columns

df = df.astype({'col1': int, 'col2': int, 'col3': int})

This will convert the 'col1', 'col2', and 'col3' columns to integers.