×

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

Base Case in Recursive function python

In this article, we will learn about Python's base case in a recursive function. Before learning this, let’s first understand what recursion is in Python and the use of recursion in...

6 minutes read.

Python String rsplit() method

Python String rsplit() method The string.rsplit() method in Python splits a string into a list, starting from the right. If the "max" parameter is not specified, this method will return the...

1 minute read.

Python Set union() method

Python Set union() method The set.union() method in Python returns a set that contains all items from the original set and all items from the specified sets. Syntax set.union(set1, set2...) Parameter set1- This parameter represents the first set...

2 minutes read.

Python Marshmallow

Python:  Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Python frozenset()

Python frozenset() class The frozenset() class in Python returns a new frozenset object, optionally with elements taken from iterable. Syntax class frozenset([iterable]) Parameter iterable: This parameter represents an iterable object, like list, set, tuple etc. Return This class returns an unchangeable...

1 minute read.

Python Combination

Python Combination Permutations and combinations are the important part of our mathematical tools. We use them often in our Python programs. In this tutorial, we will learn about combinations in Python...

6 minutes read.

Screen Rotation app Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

3 minutes read.

How to append an Array in Python

A group of objects kept at adjacent memory regions is known as an array. It is a container with a set capacity for a certain number of things, all of...

7 minutes read.

Python List clear() method

Python List clear() method The list.clear () method in Python extends the list by appending all the items from the iterable. Syntax list.clear() Parameter NA Example 1 # Python Program explaining # the list.clear() method week_list = ["Monday", "Tuesday", "Wednesday","Thursday","Friday",...

1 minute read.

Python vs HTML

Python and HTML are not comparable since they are two separate categories of programming languages. Building the structures and layouts of a web page or app requires the usage of HTML,...

8 minutes read.

Recursive Multiplication Python

Recursive Multiplication Python In this tutorial, we will learn how to write a Python program to get the multiplication of two numbers using the recursive approach. In the recursive multiplication approach, we...

2 minutes read.

Pltpcolor in Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Operator Module In Python

Introduction The operator module is used for performing operations using methods rather than utilizing operators in Python code. The operator module provides several methods for performing the operations.  The operator module contains...

7 minutes read.

wxPython Panel class

wxPython Panel class The Widgets which is shown in the frame of GUI window such as text box, buttons, static text etc. are put inside the panel class of the wxpython...

2 minutes read.

Python String lower() method

Python String lower() method The string.lower() method in Python returns a string where all characters are lower case. Syntax string.lower() Parameter NA Return This method returns a string where all characters are lower case. Example 1 # Python...

1 minute read.

Adding item to a python dictionary

The dictionary is one of python’s built-in data structures where it stores key-value pairs. A dictionary is a collection of ordered values that can be changeable. We can add, modify,...

3 minutes read.

Number pattern in Python

Number pattern in Python: This article explains how to print number patterns in Python. The FOR loop, while loop, and range() functions are used in the following Python programs to...

4 minutes read.

Conditional Statements in python

In this article, we will learn about conditional statements and how to apply conditional statements in Python. A decision-making statement is another name for a conditional statement. Decision-making is an important...

5 minutes read.

Python if statement

Python if statement Decision making is an essential feature of any programming languages. Condition checking is the strength of decision making. Python provides many decision-making statements, such as: If statementIf-else statementelif statement if statement The if statement is...

2 minutes read.

Python Arithmetic Operators

An arithmetic operator is a mathematical operator that is used to operate on two operands. Based on the operator used, action is performed on the operands, and output is delivered. Following...

3 minutes read.