×

Convert Float to Int in Python using Pandas

Introduction

To play with huge amounts of data, in python we require a tool. The tool which is available in Python is pandas. A panda is an open-source library. It is used to analyze huge datasets without any difficulty. This is the biggest advantage of pandas.

By using pandas a DataFrame can be created. A DataFrame is a table which contains all the contents of a dataset. This DataFrame helps us to visualize the ugly looking dataset into a good-looking table. So, now let us learn about how to convert the data types of the contents present in the dataset.

Creation of DataFrames

To create a DataFrame, there are few steps. They are

  • Install pandas (ignore if available)

    The command to install pandas is:
pip install pandas 
or 
python –m pip install pandas
  • Open Python idle window or any Python compiler
  • The first thing we have to do is to import pandas

       We can import pandas into the program with a command import pandas as pd

  • Create a dictionary or list or tuple for creating a DataFrame. If we have a dataset, we export it into the program with a command like:
 ds=pd.read_csv(‘File-Name’)
  • Now with a command like: 
df=pd.DataFrame(dict_name/tuple_name/list_name,columns=’Col_1’,’Col_2’….)

Example:

# step-3 importing pandas
import pandas as pd


#step-4 creating a dictionary for my convenience
DataSet={
    'players' : ['ROOT','PUJARA','ROHIT'],
    'performance':[564,227,368],
    'average':[94.00,32.43,52.57]
}
#step-5 creating a data frame
df=pd.DataFrame(DataSet);
print(df)
print(df.dtypes)

Output:

  players            performance  average
0    ROOT                 564           94.00
1  PUJARA              227            32.43
2   ROHIT                368             52.57
players         object
performance      int64
average        float64
dtype: object

Now we have learnt how to create a DataFrame in Python using pandas. Now we should convert the data types of the given dataset.

Here, we have already mentioned the column names in the dictionary itself. So, there is no need for creating the names for columns in the DataFrame block.

Our first conversion will be conversion of float values to integer values.

  • Explicit Type Conversion:

This is the first way of using the explicit type conversion method. We are going to take a loop and perform explicit type conversion method. As this is the beginner’s way of changing the data_type of given data.

Let us understand this method with the help of an example.

Example:

# step-3 importing pandas
import pandas as pd


#step-4 creating a dictionary for my convenience
DataSet={
    'players' : ['ROOT','PUJARA','ROHIT'],
    'performance':[564,227,368],
    'average':[94.00,32.43,52.57]
}
#step-5 creating a data frame


df=pd.DataFrame(DataSet);


print(df)


print('average datatype is',df['average'].dtypes)




for i in range(len(df['average'])):
    df['average'][i]=int(df['average'][i])


print(df['average'].values)


print('average datatype is',df['average'].dtypes)

Output:

  players  performance  average
0    ROOT          564    94.00
1  PUJARA          227    32.43
2   ROHIT          368    52.57
average datatype is float64


Warning (from warnings module):
SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame
 [94. 32. 52.]
average datatype is float64

But this is method is not suitable and does not yield good results. See the values [94.00,32.43,52.57] have been changed into [94. 32. 52.]. Here only the value after the given number is erased but the data type is remained same as before.

So do not prefer this method of changing datatypes in a DataFrame. A warning is occurred in the compiler because the DataFrame is read only type. So if we change the values of the DataFrame, it is against the rules of DataFrame. So, avoid this method.

  • astype() inbuilt Method:

This method helps us in changing the datatype of float to int 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.

Syntax:

This is the syntax for astype() method:

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

Example:

print(df)


print('average datatype is',df['average'].dtypes)


df['average']=df['average'].astype(int);


print(df.dtypes)


print(df)

Output:

  players  performance  average
0    ROOT          564    94.00
1  PUJARA          227    32.43
2   ROHIT          368    52.57
average datatype is float64
players        object
performance     int64
average         int32
dtype: object
  players  performance  average
0    ROOT          564       94
1  PUJARA          227       32
2   ROHIT          368       52

The astype() inbuilt method can be applied for multiple columns too.

Syntax (for multiple columns):

DataFrame_name=DataFrame_name.astype(
{‘column1’:datatype1 , ‘column2’: datatype2,…}
)

Example:

print(df)


df=df.astype({'average':int,'performance':float});


print(df.dtypes)


print(df)

Output:

    players  performance  average
0    ROOT          564    94.00
1  PUJARA          227    32.43
2   ROHIT          368    52.57
average datatype is float64
players         object
performance    float64
average          int32
dtype: object
   players  performance  average
0    ROOT        564.0       94
1  PUJARA        227.0       32
2   ROHIT        368.0       52

Conclusion:

This is the way how a datatype can be changed from float to int inside a DataFrame only using pandas.


Related Topics

Python JSON

In this tutorial, we will learn about JSON in the Python programming language. We will focus on its features, Guidelines to be kept in mind while writing its syntax, the...

3 minutes read.

Abstraction in Python

What is meant by abstraction generally? A very general notion of a thing or work is known as abstract. To be more precise, the process of having a brief idea but...

4 minutes read.

Performing Transaction Using Python MySQL

Transaction A Transaction contains a set of SQL commands used to change the data in the dataset. If we say transaction, it means that the data in the database has changed....

3 minutes read.

Python Image Processing

What is an Image? Images are the pictures that will define the world, and it has their own story, and consists of information about them and these are useful in many...

9 minutes read.

Difference between Perl and Python

Control and presently utilized for a great many undertakings, including framework organization, web improvement, network programming, and GUI improvement, and the sky is the limit from there. About Perl? Perl is a...

4 minutes read.

Python Compiler

What is Compiler? The compiler is mainly a program used to convert the source code into the machine or binary code. The source code is generally a computer program written using...

6 minutes read.

Difference between python list and tuple

In this tutorial, we will understand the key differences between python lists and tuples in python. Firstly, let us see the similarities between Lists and Tuples. Both are two data types...

4 minutes read.

Python Graph

Python Graph: In Computer Science and Mathematics, a Graph is a pictorial representation of a group of objects or elements where some elements are connected using the links. A graph...

5 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.

Flutter Python

The flutter is a frame work available in the python programming language, to create web applications, mobile apps. The flutter is generally used for the development of the backend of...

3 minutes read.

Python Parse Text File

We will learn different ways of read text records in Python. TL;DR The accompanying tells the best way to read all texts from the readme.txt document into a string: with open('readme.txt') as f: lines...

5 minutes read.

How to run Python program in CMD

How to run python program in cmd Command Prompt provides us all together with a different approach for dealing with our programs. The programs can be executed by accessing the directories. In...

3 minutes read.

Python String center() method

Python String center() method The center() method will center align the string, using a specified character (space is default) as the fill character. Syntax string.center(width[, fillchar]) Parameter width This parameter represents the length of the returned string. fillchar...

1 minute read.

How to build an Auto Clicker using Python?

What is an Auto Clicker? An Auto Clicker is software that is used for automating the click of a mouse on any particular element on the computer screen and controlling the...

8 minutes read.

Best resources to learn Numpy and Pandas in python

In this tutorial, we will discuss the different resources where we can learn about NumPy and Pandas libraries of Python in a more efficient way. NumPy NumPy, a Python library used for...

4 minutes read.

Python maketrans() function

Introduction A static method is the string maketrans() one. It is used to make a one-to-one mapping between a string's character and its translation, i.e., to define the list of characters...

5 minutes read.

How to Add Elements in List in Python?

How to Add Elements in List in Python We all are aware of the wide spectrum of applications where the data structures of Python are used. Be it lists, tuples, or...

4 minutes read.

Implementing geometric shapes into the game in python

Geometric Drawings We are trying to draw various shapes of geometry by using pygame module to implement Geometric Drawings in game. Let us revise few syntax of basic shapes, to get started...

7 minutes read.

Python Deep Copy and Shallow Copy

Assignment statements in Python create bindings between a target and an object, not copies of them. The = operator only makes a new variable that shares the reference to the...

3 minutes read.

NOT IN operator in Python

This page contains all the information about “not in” operator in python. You can also know everything about what type of operator is “not in” in python language and where...

7 minutes read.