How to convert floats to integer in Pandas

In this Python Pandas tutorial, will learn how to convert Floats to integer of DataFrame using Pandas. Also, we will cover these topics.

  • How to convert float value to an integer in Pandas
  • How to convert float to an integer in Pandas with nan
  • How to convert float to an integer in Pandas without decimal
  • How to convert float to an integer in Pandas read_csv
  • How to convert a column from float to an integer in Pandas

How to convert Floats to integer in Pandas DataFrame

  • In this Program, we will discuss how to convert float datatype to an integer in Pandas DataFrame.
  • In Python Pandas to convert float values to an integer, we can use DataFrame.astype() method. This method is used to set the data type of an existing data column in a DataFrame.
  • To do this task we can also use the input to the dictionary to change more than one column and this specified type allows us to convert the datatypes from one type to another.

Syntax:

Here is the Syntax of DataFrame.astype() method

DataFrame.astype
                (
                 dtype,
                 copy=True,
                 errors='raise'
                )
  • It consists of few parameters
    • dtype: This parameter specifies the data type to which you want to apply to the cast entire dataframe object to the same type.
    • copy: By default, it takes the ‘True’ value and it returns a copy when copy=true. If copy=False then changes to value maybe not return to another object.
    • errors: By default, it’s ‘raise’ and it includes ‘raise’ and ‘ignore’. If it is ‘raise’ then it will allow an exception. Similarly, if it is ignored then the Datatype is not to be a set.

Example:

Let’s take an example and check how to convert floats to an integer in Pandas DataFrame.

Source Code:

import pandas as pd

new_lis = [[1782.3, 224.5, 100.22], [66.2, 118.5, 457.21], 
        [276.2, 918.2, 645.55], [554.6, 5178.8, 956.86], 
        [49.7, 22.3, 9762.99], [41.36, 367.4, 900.25], 
        [37.8, 23.32, 213.90]]
df = pd.DataFrame(new_lis, columns = ['col1', 'col2', 'col3'])

print(df.astype(int))

In the above program first, we have created a list ‘new_lis’ then assign float values to it.

Now create a dataframe object and pass the column name list as an argument. Once you will print the ‘df.astype’ then the output will display only integers value.

Here is the Output of the following given code

How to convert Floats to integer in Pandas DataFrame
How to convert Floats to integer in Pandas DataFrame

Also read, How to Get first N rows of Pandas DataFrame in Python

How to convert floats value to an integer in Pandas DataFrame using apply() method

By using the Pandas.apply() method we can easily convert float datatype to an integer in Pandas DataFrame.

Syntax:

Here is the Syntax of DataFrame.apply() method

DataFrame.apply
               (
                func,
                axis=0,
                raw=False,
                result_type=None,
                args=(),
               )

Source Code:

import pandas as pd
import numpy as np

new_lis = [[1782.3, 224.5, 100.22], [66.2, 118.5, 457.21], 
        [276.2, 918.2, 645.55], [554.6, 5178.8, 956.86], 
        [49.7, 22.3, 9762.99], [41.36, 367.4, 900.25], 
        [37.8, 23.32, 213.90]]
df = pd.DataFrame(new_lis, columns = ['col1', 'col2', 'col3'])
df['col2'] = df['col2'].apply(np.int64)
df['col1'] = df['col1'].apply(np.int64)
df['col3'] = df['col3'].apply(np.int64)
print(df)

In the above code, we have selected all the columns which are available in the list, and to convert float type values into integer values, we can easily use the df. apply() method.

Here is the implementation of the following given code

How to convert Floats to integer in Pandas DataFrame
How to convert Floats to integer in Pandas DataFrame

Read Pandas replace nan with 0

Convert float value to an integer in Pandas

  • Here we can see how to convert float value to an integer in Pandas.
  • To perform this particular task we can apply the method DataFrame.astype(). This method will help the user to convert the float value to an integer. In Python, this method is used to cast an object in the Pandas DataFrame to a different data type like integer and this function also changes the datatype of the dataframe object to a particular datatype.

Source Code:

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.rand(3,4), columns=list("Lmno"))
print(df)
df[list("Lmno")] = df[list("Lmno")].astype(int)

print("After updating Datafarme",df)

In the above program, we have imported pandas and numpy library and then create a dataframe object ‘df’ in which we have used random() function for creating float values. Along with that we have assigned the df. astype() method to convert float values with integer values.

Here is the Screenshot of the following given code

Convert float value to an integer in Pandas
Convert float value to an integer in Pandas

Read How to Add a Column to a DataFrame in Python Pandas

How to convert float to an integer in Pandas with nan

  • Let us see how to convert float nan value with an integer in Pandas DataFrame.
  • By using Dataframe.astype() method we can solve this problem. In this example, we have created a pandas series and assign nan and floating values to it. Now declare a variable ‘result’ and use df.astype() function for converting float nan values to integer.

Source Code:

import pandas as pd
import numpy as np
   
new_val = pd.Series([78.0, 49.0, np.nan, 26.0,np.nan,72.0])
result = new_val.astype('Int32')
print(result)

Here is the execution of the following given code

How to convert float to an integer in Pandas with nan
How to convert float to an integer in Pandas with nan

As you can see in the Screenshot the output will display only an integers value

Read How to Convert Pandas DataFrame to NumPy Array in Python

How to convert float to an integer in Pandas without decimal

  • In this Program, we will discuss how to convert float values to an integer in Pandas dataframe without decimal.
  • In this example first, we have created a dataframe and assign a string value to it. Now we want to convert these strings to float numbers. To do this we have used the df.astype(float) method to get the integer numbers.
  • Now use the df.astype(float).sum method it is used to set the data type of an existing data column in a DataFrame.

Example:

import pandas as pd
import numpy as np
df = pd.DataFrame([
        ['9', '3', '897'],
        ['28', '67', '91'],
        ['67', '567', '43']
    ])
df.astype(float).sum().astype(str)
pd.options.display.float_format = '{:,.0f}'.format
df.astype(float).sum()
print (df)

Here is the execution of the following given code

How to convert float to an integer in Pandas without decimal
How to convert float to an integer in Pandas without decimal

Read Get index Pandas Python

How to convert float to an integer in Pandas read_csv

  • Here we can see how to convert float to an integer in Pandas dataframe by using read_csv mode.
  • In this example first, we created a CSV file in which we have assigned a floating value. Now use the df.astype() method to convert floating values to an integer.

Source Code:

import pandas as pd
import numpy as np

df = pd.read_csv('test1.csv')
result = df.astype(int)
print(result)

In the above program, we have imported both the Python library and then create and variable ‘df’ in which we have read the CSV file and the delimiter is commas in the file name.

You can create your CSV file and put float values in it. After that apply the df.astype() method to solve this problem.

Here is the Screenshot of the CSV file

How to convert float to an integer in Pandas read_csv
How to convert float to an integer in Pandas read_csv

Implementation:

How to convert float to an integer in Pandas read_csv
How to convert float to an integer in Pandas read_csv

Read Python Pandas Write DataFrame to Excel

How to convert a column from float to an integer in Pandas

  • In this Program, we will discuss how to convert a column from float to an Integer value in Pandas DataFrame.
  • By using the Pandas.apply() method we can allow the user to pass a method and apply it to values of the Pandas DataFrame.

Syntax:

Here is the Syntax of Pandas. apply() method

DataFrame.apply
               (
                func,
                axis=0,
                raw=False,
                result_type=None,
                args=(),
               )

Source Code:

import pandas as pd
import numpy as np

new_lis = [[6732.3, 224.5, 100.22], [66.2, 118.5, 457.21], 
        [3489.2, 918.2, 645.55], [554.6, 5178.8, 956.86], 
        [883.7, 22.3, 9762.99], [41.36, 367.4, 900.25], 
        [189.8, 23.32, 213.90]]
df = pd.DataFrame(new_lis, columns = ['val1', 'val2', 'val3'])
df['val2'] = df['val2'].apply(np.int64)
df['val1'] = df['val1'].apply(np.int64)
df['val3'] = df['val3'].apply(np.int64)
print(df)

In the above code, we have selected all the columns which are available in the list, and to convert float type values into integer values, we can easily use the df. apply() method. Once you will print ‘df’ then the output will display all the column’s values.

You can refer to the below Screenshot

How to convert a column from float to an integer in Pandas
How to convert a column from float to an integer in Pandas

You may like the following Python Pandas tutorials:

In this Python Pandas tutorial, will learn how to convert Floats to integer of DataFrame using Pandas. Also, we will cover these topics.

  • How to convert float value to an integer in Pandas
  • How to convert float to an integer in Pandas with nan
  • How to convert float to an integer in Pandas without decimal
  • How to convert float to an integer in Pandas read_csv
  • How to convert a column from float to an integer in Pandas