In this tutorial, we will learn how to convert float to int in a Python DataFrame.
Converting float to int in a DataFrame is a common operation while working with real-world data, especially when dealing with datasets that contain numerical values with decimals and we require whole numbers for further analysis.
To achieve this, we will use the pandas library. If you haven’t installed pandas already, you can do so using pip:
pip install pandas
Step 1: Importing pandas library and reading data
First, let’s begin by importing the pandas library, reading and displaying the data.
1 2 3 4 5 6 7 8 |
import pandas as pd # Reading data from a CSV data = {'A': [1.2, 2.7, 3.3], 'B': [4.5, 5.6, 6.8]} df = pd.DataFrame(data) # Display DataFrame print(df) |
The DataFrame will look like this:
A B 0 1.2 4.5 1 2.7 5.6 2 3.3 6.8
Step 2: Converting float to int using the astype() method
We can use the astype() method to convert the float values to int.
1 2 3 4 5 6 |
# Converting float values to int df['A'] = df['A'].astype(int) df['B'] = df['B'].astype(int) # Displaying the modified DataFrame print(df) |
The modified DataFrame will look like this:
A B 0 1 4 1 2 5 2 3 6
Step 3: Converting float to int using the round() and map() methods
Another way to convert the float values to int is by using round() and map() methods. The round() method will round off the float values, and then we will use the map() method to convert rounded values to ints.
1 2 3 4 5 6 7 8 9 10 |
# Reading data from a CSV data = {'A': [1.2, 2.7, 3.3], 'B': [4.5, 5.6, 6.8]} df = pd.DataFrame(data) # Converting float values to int df['A'] = df['A'].map(lambda x: round(x)) df['B'] = df['B'].map(lambda x: round(x)) # Displaying the modified DataFrame print(df) |
The modified DataFrame will look like this:
A B 0 1 4 1 3 6 2 3 7
Full Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import pandas as pd # Reading data from a CSV data = {'A': [1.2, 2.7, 3.3], 'B': [4.5, 5.6, 6.8]} df = pd.DataFrame(data) # Converting float values to int using astype() df['A'] = df['A'].astype(int) df['B'] = df['B'].astype(int) # Displaying the modified DataFrame print(df) # Reading data from a CSV data = {'A': [1.2, 2.7, 3.3], 'B': [4.5, 5.6, 6.8]} df = pd.DataFrame(data) # Converting float values to int using round() and map() df['A'] = df['A'].map(lambda x: round(x)) df['B'] = df['B'].map(lambda x: round(x)) # Displaying the modified DataFrame print(df) |
Conclusion:
In this tutorial, we have learned how to convert float to int in Python DataFrame using the astype() method and the combination of round() and map() methods.
Converting float to int is an essential operation while dealing with datasets containing numerical data and helps in better analysis and visualization.