Convert floats to ints in Pandas?
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:
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
Watch a video course
Python - The Practical Guide
To convert the values in this column to integers, you can use the following code:
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:
df = df.astype({'col1': int, 'col2': int, 'col3': int})
This will convert the 'col1'
, 'col2'
, and 'col3'
columns to integers.