×

Convert int to Float in Python using Pandas

Introduction

We have already learnt about how to convert float variables to int. Now let us know how to convert int variables to float

So let us create another Dataset on which we can perform a few operations.

Code:

'''
1.) downaload pandas if unavailable
2.)Open Python idle window
3.) import pandas library
'''
import pandas as pd


# Created a Dictionary for creating a DataFrame
DataSet={
    'players':['root','pujara','rohit'],
    'SR':[60.71,32.43,42.49],
    'Avg':[94.00,36.97,52.57],
    'runs':[564,227,368]
    }


# DataFrame Creation
df=pd.DataFrame(DataSet)
print(df)

Output:

    players     SR    Avg  runs
0    root  60.71  94.00   564
1  pujara  32.43  36.97   227
2   rohit  42.49  52.57   368

So as usual the way of converting a variable using explicit type conversion is not used. This type of conversion cannot be used as DataFrame is in read only format. There are two methods which can be used.

They are:

  1. astype(Data_Type)
  2. to_numeric()

astype() Method

This method helps us in changing the datatype of int to float directly in the DataFrame. astype() is inbuilt method which is present in the pandas library. This inbuilt method helps us to convert float to int, int to float etc. This method is present in DataFrame directly. We can use dot(.) operator to use this kind of method

Syntax:

DataFrame_name[‘column_name’]=DataFrame_name[‘column_name’].astype(Data_Type)

Code:

print(df)


print(df.dtypes)


df['runs']=df['runs'].astype(float)
print(df.dtypes

Output:

  players     SR    Avg  runs
0    root  60.71  94.00   564
1  pujara  32.43  36.97   227
2   rohit  42.49  52.57   368


players     object
SR         float64
Avg        float64
runs         int64
dtype: object
#After Conversion
players     object
SR         float64
Avg        float64
runs       float64
dtype: object

This is the way how a variable in DataFrame can be converted from int to float.

How to Perform Multiple data_types Conversions in a DataFrame?

Yes, we can convert multiple data_types in a DataFrame by using astype() method. Just there is a small change in syntax for astype() method. First let us know the syntax of this type of datatype conversion.

Syntax:

DataFrame_name=DataFram_name.astype({‘column_name’ :’data_type1’,’column_name’: ‘data_type2’……})

Let us explain this process with an example.

Example:

print(df.dtypes)


print(df)


df=df.astype({'SR':'int','runs':'int'})


print(df.dtypes)

Output:

players     object
SR         float64
Avg        float64
runs         int64
dtype: object
  players     SR    Avg  runs
0    root  60.71  94.00   564
1  pujara  32.43  36.97   227
2   rohit  42.49  52.57   368
players     object
SR           int32
Avg        float64
runs         int32
dtype: object

to_numeric()

This is a method which is already in-built in Python library. to_numeric is also is used to change the data_type of a column. To use this method, we need to know the syntax of the to_numeric method.

Syntax:

pandas.to_numeric(DataFrame[‘column_name’],

Example:

df=pd.DataFrame(DataSet)


print(df.dtypes)


df['Avg']=pd.to_numeric(df['Avg'],downcast='int')


print(df.dtypes)

Output:

players     object
SR         float64
Avg          int64
runs         int64
dtype: object
players     object
SR         float64
Avg        float32
runs         int64
dtype: object

This is how we convert int to float and float to int


Related Topics

Read Text files in Python

In Python, there are many ways to read text files. Before going into the detailed structure of reading a text file, let us understand how reading text files takes place...

4 minutes read.

How to Install Python

Python Installation Guide Step by Step Installing Python is quite simple and easy. In this tutorial, we will show stepwise procedure to install Python and set up the Python environment in different...

2 minutes read.

Assertion Errors and Attribute Errors in Python

Assertion Error in Python In Python, the assert condition is used to continue the execution if the given statement displays true. If the assert statement displays false, it raises Assertion Error...

3 minutes read.

Python Breakpoint

Introduction In Python 3.7, a brand-new created function called breakpoint() was added. Due to the close relationship between both the executable and the code of a debugging component, debugging Python programming...

4 minutes read.

How to convert integer to float in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

5 minutes read.

How to Compare two Lists in Python?

How to Compare two Lists in Python The list is a data structure in Python that can hold values of different data types. The values are enclosed in square brackets [...

4 minutes read.

Python Word Tokenizer

Python Overview Python is an Object-Oriented high-level language. Python is designed to be highly beginner-friendly. Python has an English-like syntax, which is very easy to read. Python is an interpreted language...

4 minutes read.

Nested Tuple in Python

If you are a Python learner, this page contains all the information that helps you know about nested tuple and how to access it in python. What is a Tuple? Multiple items...

4 minutes read.

Function annotations() in Python

What is Function Annotations? Function annotations provide a way related to different parts of a function at compile time with arbitrary Python expressions. It doesn’t have life in Python runtime execution....

3 minutes read.

List Comprehension in Python

Sometimes we need new lists that are completely based on previously existing lists, so to perform this operation successfully, some of the programming languages come with a syntactic construct known...

5 minutes read.

Python program to display ASCII value of the character

Python program to display ASCII value of the character The full form of ASCII is American Standard Code for Information Interchange. This example explains a program in Python to find the...

1 minute read.

Introducing modern python computing in simple packages

Python is the language for newly evolving technologies and has become one of the most popular computer languages in the world. Python is used in everything right from a simple...

3 minutes read.

Data Distribution in python

Before discussing data distribution, we will discuss each word that is data and Distribution. What is meant by data? A collection of raw facts and figures is called data. The word "raw"...

18 minutes read.

chr() and ord() Functions in Python

Python language contains many built-in functions which we use for many programs to work efficiently. The chr() and ord() are a few built-in functions in Python that are used for...

4 minutes read.

Python Read CSV file

The CSV stands for “comma-separated value,” which is defined as a simple file format that is used to store data into a tabular form such as a database or spreadsheet. It is...

7 minutes read.

Python Fit Transform

In machine learning, fit (), transform(), fit transform () methods are provided by scikit learn package. This package is used in model fitting and data processing. These methods are implemented...

2 minutes read.

Python Set update() method

Python Set update() method The set.update() method in Python updates the current set, by adding items from another set. If an element is common in both the sets, only one appearance of this item...

1 minute read.

Difference Between Python and Scala

What is Python? Python is a high-level general-purpose interpreted programing language. It is used for multi general-purpose work such as language construct as well as its object-oriented approach aims to help...

4 minutes read.

Python List extend() method

Python List extend() method The list.extend() method extends the list by appending all the items from the iterable. Syntax list.extend(iterable) Parameter iterable: It is a required parameter which represents any iterable unlike list, set, tuple, etc. Example 1 # Python...

1 minute read.

Python Logical Operators

In python, there are many operators which we use in our program. Operators are used in manipulating a particular value or operand. Logical operators are used mainly to evaluate an...

7 minutes read.