## The self variable in Python explained with Python tips

Rated 4.0/5 based on 10 customer reviews

# The self variable in Python explained with Python tips

12K

If you have been working on Python, you might have across the self variable. You can find it in method definitions and in initializing variables. However, before coming to the self variable, let us have an idea about classes and instances in Python.

## What are Instance methods and Class methods in Python?

You might have heard of instances and classes while working on Python. Class variables are defined within a class and they are shared with all the instances (objects) of the class whereas instance variables are owned by the instances of a class. For different instances, the instance variables are different.

Likewise, Python also contains class methods and instance methods. The class methods inform about the status of the class. On the other hand, instance methods are to set or get details about instances or objects.

If you want to define an instance method, the foremost parameter of the method should always have to be self. Let us understand this with the help of example code –

class myClass:
def instance_method(self):
return “Instance method is called”, self 

The method “instance_method” is a regular instance method. The method accepts one single parameter – self. The self variable points to an instance of the class myClass when the method is revoked. Though the method takes only one parameter here, it can also accept more than one parameter.

The instance methods can easily access different attributes and other methods on the same object with the help of the self variable. The self variable also has the power to modify the state of an object and using the self.__class__  attribute, instance methods can also access the class. Thus, the instance methods are also able to modify the class state.

Now, let us see what happens when we call “instance_method”:

>>>obj = myClass()
>>>obj.instance_method()
('Instance method is called', <myClass instance at 1x09255d103>) 

This shows that “instance_method” can access the object instance (printed as <myClass instance>) through the self parameter. What happens is that the self parameter is replaced with the instance object obj when the method is called. However, if you pass the instance object manually, you will get the same result as before:

>>>myClass.instance_method(obj)
('Instance method is called', <myClass instance at 1x09255d103>) 

Note that self is actually not a defined keyword in Python but a convention.

## What is Self in Python?

Unlike this variable in C++, self is not a keyword rather it is more of a coding convention. It represents the instance or objects of a class and binds the attributes of a class with specific arguments. The use of self variable in Python helps to differentiate between the instance attributes (and methods) and local variables.

If you do not want the variables of your class to be shared by all instances of the class, you can declare variables within your class without self. Let us understand this with an example:

class Car:
def __init__(self, model):
self.model = model
def Car_info(self):
print("Model : ", self.model) 

Here, we have declared a class Car with one instance variable self.model = model. The value of the instance variable will be unique to the instance objects of the class that might be declared. However, if you want the variables to be shared by all instances of the class, you need to declare the instance variables without self. Otherwise, it would be ambiguous since all cars will have the same model.

### Need for Self in Python

The self variable is used to represent the instance of the class which is often used in object-oriented programming. It works as a reference to the object. Python uses the self parameter to refer to instance attributes and methods of the class.

Unlike other programming languages, Python does not use the “@” syntax to access the instance attributes. This is the sole reason why you need to use the self variable in Python. The language contains methods that allow the instance to be passed automatically but not received automatically.

### Explicit definition of self

The Zen of Python says “Explicit is better than Implicit”. Programmers of other languages often ask why self is passed as an explicit parameter every time to define a method. There are a few reasons for this.

Firstly, since Python uses a method or instance attribute instead of a local variable when we read self.name or self.age, it makes it absolutely clear you are using an instance variable or method even if you have no knowledge about the class definition.

Secondly, if you explicitly refer or call a method from a particular class in Python, you do not need to use any special syntax for that.

Finally, the third reason is that the explicit definition of self helps Python understand whether to assign to an instance variable or to a local variable. In simpler terms, local variables and instances exist in two separate namespaces and we need to inform Python which namespace should be used.

## What is a Python class self constructor?

The self variable in Python can also be used to access a variable field within the class definition. Let us understand this with the help of example code:

class Student:

    def __init__(self, Alex):
self.name = Alex    #name created in constructor
def get_student_name(self):
return self.name 

In the example above, self refers to the variable age of the class Student. The variable age is local to the method. While the method is running, the variable age exists within the class.

If there is a variable within a method, the self variable will not work. If you wish to define global fields, you need to define variables outside the class methods.

## Is self a keyword in Python?

There is a question that always hovers among Python programmers. Is self actually a keyword in Python?

Unlike other programming languages like C++, where self is considered to be a keyword, in Python it is a convention that programmers tend to follow. It is basically a parameter in a method definition. However, you can use any other name in place of self like another or me or anything else for the first parameter of a method. Another reason why it is suggested by most people is that it enhances the readability of your code.

Let us see an example to understand it:

class myClass:
def show(another):
print(“another is used in place of self”)  

If you compare this code with the code for the Python class self constructor, you will notice that here we have used the name another in place of self. Now let us create an object of this class and see the output:

object = myClass()
object.show()

another is used in place of self

You can see that the program works even if we use some other name in place of the self variable. It works exactly the same way as the self variable does.

## Why "self" should be used as the first parameter of instance methods in python

This can be understood by the below example. We have a Rectangle class which defines a method area to calculate the area :

class Rectangle ():
def __init__(self,x = 0,y = 0):
self.x = x
self.y = y
def area (self):
"""Find area of rectangle"""
return (self.x * self.y)
rec1=Rectangle(6,10)
print ("Area is:", rec1.area()) 

Output:

Area is: 60

In the above example, __init__() defines three parameters but only 2 arguments are passed (6 and 10). Similarly, area () requires one but no arguments are passed.

Rectangle.area and rec1.area in the above example are different and not exactly the same.

>>> type(Rectangle.area )
<class 'function'>
>>> type(rec1.area)
<class 'method'> 

Here, the first one is a function and the second one is a method. A unique feature of Python is that the object itself is passed as the first argument to the corresponding function.

In the above example, the method call:  rec1.area()is equivalent to:  Rectangle.area(rec1).

Generally, when the method is called with some arguments, the corresponding class function is called by placing the method's object before the first argument.

Therefore: obj.method(args) becomes Class.method(obj, args)

This is the reason the first parameter of a function in a class must be the object itself. Writing this parameter as self is merely a convention and not a keyword so it has no special meaning in Python. We could use other names (like this, that) but it is not preferred as it degrades code readability.

## Should we pass self to a method?

Since we can use any other name instead of using the self variable, then what will happen if we just pass self to a method definition. Let us consider the class myClass we have used earlier.

A method named something is defined within the class with a parameter another and two arguments:

class myClass:
def something(another, argument1, argument2):
pass 

Now, let us declare an instance obj of myClass and call the method something with the help of the instance object:

obj = myClass()
obj.something(argument1, argument2) 

Python performs an internal work on the method call and converts it into something like this:

myClass.something(obj, argument1, argument2)

This shows that another variable (used in place of self) refers to the instance object of the class.

Note that the pass keyword used in the method something does nothing. It is used as a dummy in situations where you do not want any operation to be performed but there is a syntax requirement of a certain programming element.

## How can we skip self in Python?

Consider a situation where the instance method does not need to have access to the instance variables. In such cases, we can consider skipping the self variable in defining methods. Let us have a clear understanding of the fact with example code:

class Vehicle:
def Car():
print(“Rolls Royce 1948”)
obj = Vehicle()
print(“Complete”) 

If you run the following code, the output will be as follows:

Complete

We have not declared the self variable here but there is still no error in the program and the output comes out fine. However, what will be the case if we call the Car() method:

obj = Vehicle()
obj.Car() 

When we compile the code after calling the Car() method, it shows an error like this:

Traceback (most recent call last):
File "<string>", line 11, in <module>
TypeError: Car() takes 0 positional arguments but 1 was given 

The output shows an error since the method Car() takes 0 positional arguments but we have given 1 positional argument to it. This is because when the instance obj is created, it is automatically passed as the first argument to the method Car() even if we have not declared the self variable.

However, if you try to access the instance method Car() with the help of the class reference, there will be no errors and the program will work fine:

class Vehicle:
def Car():
print("Rolls Royce 1948")
obj = Vehicle()
Vehicle.Car()
Rolls Royce 1948 

## Difference between self and __init__

self : self represents the instance of the class. By using the "self" keyword all the attributes and methods of the python class can be accessed.

__init__ : "__init__" is a reserved method in python classes. It is known as a constructor in object oriented concepts. This method is called when an object is created from the class and allows the class to initialize class attributes ..

Usage of "self" in class to access the methods and attributes:

class Rectangle:
def __init__(self, length, breadth, cost_per_unit =0):
self.length = length
self.cost_per_unit = cost_per_unit
def perimeter(self):
return 2 * (self.length + self.breadth)
def area(self):
def calculate_cost(self):
area = self.area()
return area * self.cost_per_unit
# length = 40 cm, breadth = 30 cm and 1 cm^2 = Rs 100
r = Rectangle(40, 30, 100)
print("Area of Rectangle:",r.area())
print("Cost of rectangular field is : Rs ",r.calculate_cost()) 

Output:

Area of Rectangle: 1200
Cost of rectangular field is : Rs  120000 

We have created an object of Rectangle class. While creating the Rectangle object, we passed 3 arguments – 40,30,100; all these arguments are passed to "__init__"method to initialize the object.

Here, the keyword "self” represents the instance of the class. It binds the attributes with the given arguments.

Self represents the same object or instance of the class. If you see, inside the method "area” , self.length" is used to get the value of the attribute "length".  attribute "length" is bind to the object (instance of the class) at the time of object creation. "self" represents the object inside the class. "self" works just like "r" in the statement “r = Rectangle(40,30, 100)".  If you see the method definition "def area(self): ” , here "self" is used as a parameter in the method because whenever we call the method,  the object (instance of class) is automatically passed as a first argument along with other arguments of the method. If no other arguments are provided only "self" is passed to the method. That's the reason "self" is used to call the method inside the class("self.area()").  We used object (instance of class) to call the method outside of the class definition("r.area()").

"r" is the instance of the class when the method "r.area()” is called; the instance "r" is passed as first argument in the place of self.

Miscellaneous Implementations of self

Let us now discuss some of the miscellaneous implementations of the self variable.

Similar variables for Class Method and Static Method

A class method is a method that is bound to the class. Let us understand a class method with an example –

class myClass:
@classmethod
def classmethod(cls):
return “Class Method is called”
obj.classmethod() 

The same behavior of the self variable is present with the Class methods too but the only difference is that for class methods, the convention is to use cls as the variable name instead of self.

The class methods take a cls parameter instead of the self parameter. When the method is called, it points to the class. The class method cannot modify the object state but it can modify the class state of all the class instances.

On the other hand, static methods are self-sufficient functions and this type of method takes neither a self nor a cls parameter. Let us see an example of a static method –

class myClass:
@staticmethod
def staticmethod():
return “Static Method is called”
obj.staticmethod() 

Since a static method does not accept any parameter, they cannot modify object state or even class state. They are primarily used to namespace different methods and Python restricts them in the data they can access.

Note that both the methods here are marked with @classmethod and @staticmethod decorators to flag it as a class method and static method respectively.

The self variable is bound to the current instance

The self variable allows us to access the properties of the current instance. Let us understand this with an example –

class Person:
def __init__(self, n):
self.name = n
def walk(self):
print(f“{self.name} is walking”)
obj1 = Person(“Alex”)
obj2 = Person(“Charles”)
obj1.walk()
obj2.walk()
Alex is walking
Charles is walking 

Here, we have a class Person with two methods __init__ and walk declared with the self parameter. We have created two different instances of the class – obj1 and obj2. When the first instance is revoked, “Alex” is printed with the method walk() whereas when the second instance is revoked, “Charles” gets printed with the properties of the instance method walk().

## Tips about the Python self variable

Since we have now reached the end of the article, let me give you some tips about when to use and when not to use the self variable in Python.

### Use self when:

• you define an instance method, since it is passed automatically as the first parameter when the method is called;
• you reference a class or an instance attribute from inside an instance method;
• you want to refer to instance variables and methods from other instance methods.

### Don’t use self when:

• you want to call an instance method normally;
• referencing a class attribute inside the class definition but outside an instance method;
• you are inside a static method.

## Conclusion

Let us recap the key points we have covered in this article, namely:

• Instances and Classes in Python.
• Self variable and its importance.
• The explicitness of the self variable.
• Python class self constructor.
• Passing self as a method.
• Skipping self in Python.
• Variables used for Class methods and Static methods.
• Bounding of self to the current instance.
• When to use and when not to use self in Python.

With good knowledge about the self variable in Python and its internal working in Python, it is now time for some practice. If you, however, wish to know more about Python self, you can head right on to the official documentation of Python.

Happy coding!

### Priyankur Sarkar

Data Science Enthusiast

Priyankur Sarkar loves to play with data and get insightful results out of it, then turn those data insights and results in business growth. He is an electronics engineer with a versatile experience as an individual contributor and leading teams, and has actively worked towards building Machine Learning capabilities for organizations.

## How to Round Numbers in Python

While you are dealing with data, sometimes you may come across a biased dataset. In statistics, bias is whereby the expected value of the results differs from the true underlying quantitative parameter being estimated. Working with such data can be dangerous and can lead you to incorrect conclusions. To learn more about various other concepts of Python, go through our Python Tutorials or enroll to our Python Certification course online.There are many types of biases such as selection bias, reporting bias, sampling bias and so on. Similarly, rounding bias is related to numeric data. In this article we will see:Why is it important to know the ways to round numbersHow to use various strategies to round numbersHow data is affected by rounding itHow to use NumPy arrays and Pandas DataFrames to round numbersLet us first learn about Python’s built-in rounding process.About Python’s Built-in round() FunctionPython Programming offers a built-in round() function which rounds off a number to the given number of digits and makes rounding of numbers easier. The function round() accepts two numeric arguments, n and n digits and then returns the number n after rounding it to ndigits. If the number of digits are not provided for round off, the function rounds off the number n to the nearest integer.Suppose, you want to round off a number, say 4.5. It will be rounded to the nearest whole number which is 5. However, the number 4.74 will be rounded to one decimal place to give 4.7.It is important to quickly and readily round numbers while you are working with floats which have many decimal places. The inbuilt Python function round() makes it simple and easy.Syntaxround(number, number of digits)The parameters in the round() function are:number - number to be roundednumber of digits (Optional) - number of digits up to which the given number is to be rounded.The second parameter is optional. In case, if it is missing then round() function returns:For an integer, 12, it rounds off to 12For a decimal number, if the last digit after the decimal point is >=5 it will round off to the next whole number, and if =5 print(round(5.476, 2))     # when the (ndigit+1)th digit is  1 print(round("x", 2)) TypeError: type str doesn't define __round__ methodAnother example,print(round(1.5)) print(round(2)) print(round(2.5))The output will be:2 2 2The function round() rounds 1.5 up to 2, and 2.5 down to 2. This is not a bug, the round() function behaves this way. In this article you will learn a few other ways to round a number. Let us look at the variety of methods to round a number.Diverse Methods for RoundingThere are many ways to round a number with its own advantages and disadvantages. Here we will learn some of the techniques to rounding a number.TruncationTruncation, as the name means to shorten things. It is one of the simplest methods to round a number which involves truncating a number to a given number of digits. In this method, each digit after a given position is replaced with 0. Let us look into some examples.ValueTruncated ToResult19.345Tens place1019.345Ones place1919.345Tenths place19.319.345Hundredths place19.34The truncate() function can be used for positive as well as negative numbers:>>> truncate(19.5) 19.0 >>> truncate(-2.852, 1) -2.8 >>> truncate(2.825, 2) 2.82The truncate() function can also be used to truncate digits towards the left of the decimal point by passing a negative number.>>> truncate(235.7, -1) 230.0 >>> truncate(-1936.37, -3) -1000.0When a positive number is truncated, we are basically rounding it down. Similarly, when we truncate a negative number, the number is rounded up. Let us look at the various rounding methods.Rounding UpThere is another strategy called “rounding up” where a number is rounded up to a specified number of digits. For example:ValueRound Up ToResult12.345Tens place2018.345Ones place1918.345Tenths place18.418.345Hundredths place18.35The term ceiling is used in mathematics to explain the nearest integer which is greater than or equal to a particular given number. In Python, for “rounding up” we use two functions namely,ceil() function, andmath() functionA non-integer number lies between two consecutive integers. For example, considering a number 5.2, this will lie between 4 and 5. Here, ceiling is the higher endpoint of the interval, whereas floor is the lower one. Therefore, ceiling of 5.2 is 5, and floor of 5.2 is 4. However, the ceiling of 5 is 5.In Python, the function to implement the ceiling function is the math.ceil() function. It always returns the closest integer which is greater than or equal to its input.>>> import math >>> math.ceil(5.2) 6 >>> math.ceil(5) 5 >>> math.ceil(-0.5) 0If you notice you will see that the ceiling of -0.5 is 0, and not -1.Let us look into a short code to implement the “rounding up” strategy using round_up() function:def round_up(n, decimals=0):     multiplier = 10 ** decimals     return math.ceil(n * multiplier) / multiplierLet’s look at how round_up() function works with various inputs:>>> round_up(3.1) 4.0 >>> round_up(3.23, 1) 3.3 >>> round_up(3.543, 2) 3.55You can pass negative values  to decimals, just like we did in truncation.>>> round_up(32.45, -1) 40.0 >>> round_up(3352, -2) 3400You can follow the diagram below to understand round up and round down. Round up to the right and down to the left.Rounding up always rounds a number to the right on the number line, and rounding down always rounds a number to the left on the number line.Rounding DownSimilar to rounding up we have another strategy called rounding down whereValueRounded Down ToResult19.345Tens place1019.345Ones place1919.345Tenths place19.319.345Hundredths place19.34In Python, rounding down can be implemented using a similar algorithm as we truncate or round up. Firstly you will have to shift the decimal point and then round an integer. Lastly shift the decimal point back.math.ceil() is used to round up to the ceiling of the number once the decimal point is shifted. For “rounding down” we first need to round the floor of the number once the decimal point is shifted.>>> math.floor(1.2) 1 >>> math.floor(-0.5) -1Here’s the definition of round_down():def round_down(n, decimals=0):     multiplier = 10 ** decimals return math.floor(n * multiplier) / multiplierThis is quite similar to round_up() function. Here we are using math.floor() instead of math.ceil().>>> round_down(1.5) 1 >>> round_down(1.48, 1) 1.4 >>> round_down(-0.5) -1Rounding a number up or down has extreme effects in a large dataset. After rounding up or down, you can actually remove a lot of precision as well as alter computations.Rounding Half UpThe “rounding half up” strategy rounds every number to the nearest number with the specified precision, and breaks ties by rounding up. Here are some examples:ValueRound Half Up ToResult19.825Tens place1019.825Ones place2019.825Tenths place19.819.825Hundredths place19.83In Python, rounding half up strategy can be implemented by shifting the decimal point to the right by the desired number of places. In this case you will have to determine whether the digit after the shifted decimal point is less than or greater than equal to 5.You can add 0.5 to the value which is shifted and then round it down with the math.floor() function.def round_half_up(n, decimals=0):     multiplier = 10 ** decimals return math.floor(n*multiplier + 0.5) / multiplierIf you notice you might see that round_half_up() looks similar to round_down. The only difference is to add 0.5 after shifting the decimal point so that the result of rounding down matches with the expected value.>>> round_half_up(19.23, 1) 19.2 >>> round_half_up(19.28, 1) 19.3 >>> round_half_up(19.25, 1) 19.3Rounding Half DownIn this method of rounding, it rounds to the nearest number similarly like “rounding half up” method, the difference is that it breaks ties by rounding to the lesser of the two numbers. Here are some examples:ValueRound Half Down ToResult16.825Tens place1716.825Ones place1716.825Tenths place16.816.825Hundredths place16.82In Python, “rounding half down” strategy can be implemented by replacing math.floor() in the round_half_up() function with math.ceil() and then by subtracting 0.5 instead of adding:def round_half_down(n, decimals=0):     multiplier = 10 ** decimals return math.ceil(n*multiplier - 0.5) / multiplierLet us look into some test cases.>>> round_half_down(1.5) 1.0 >>> round_half_down(-1.5) -2.0 >>> round_half_down(2.25, 1) 2.2In general there are no bias for both round_half_up() and round_half_down(). However, rounding of data with more number of ties results in bias. Let us consider an example to understand better.>>> data = [-2.15, 1.45, 4.35, -12.75]Let us compute the mean of these numbers:>>> statistics.mean(data) -2.275Now let us compute the mean on the data after rounding to one decimal place with round_half_up() and round_half_down():>>> rhu_data = [round_half_up(n, 1) for n in data] >>> statistics.mean(rhu_data) -2.2249999999999996 >>> rhd_data = [round_half_down(n, 1) for n in data] >>> statistics.mean(rhd_data) -2.325The round_half_up() function results in a round towards positive infinity bias, and round_half_down() results in a round towards negative infinity bias.Rounding Half Away From ZeroIf you have noticed carefully while going through round_half_up() and round_half_down(), neither of the two is symmetric around zero:>>> round_half_up(1.5) 2.0 >>> round_half_up(-1.5) -1.0 >>> round_half_down(1.5) 1.0 >>> round_half_down(-1.5) -2.0In order to introduce symmetry, you can always round a tie away from zero. The table mentioned below illustrates it clearly:ValueRound Half Away From Zero ToResult16.25Tens place2016.25Ones place1616.25Tenths place16.3-16.25Tens place-20-16.25Ones place-16-16.25Tenths place-16.3The implementation of “rounding half away from zero” strategy on a number n is very simple. All you need to do is start as usual by shifting the decimal point to the right a given number of places and then notice the digit d immediately to the right of the decimal place in this new number. Here, there are four cases to consider:If n is positive and d >= 5, round upIf n is positive and d < 5, round downIf n is negative and d >= 5, round downIf n is negative and d < 5, round upAfter rounding as per the rules mentioned above, you can shift the decimal place back to the left.There is a question which might come to your mind - How do you handle situations where the number of positive and negative ties are drastically different? The answer to this question brings us full circle to the function that deceived us at the beginning of this article: Python’s built-in  round() function.Rounding Half To EvenThere is a way to mitigate rounding bias while you are rounding values in a dataset. You can simply round ties to the nearest even number at the desired precision. Let us look at some examples:ValueRound Half To Even ToResult16.255Tens place2016.255Ones place1616.255Tenths place16.216.255Hundredths place16.26To prove that round() really does round to even, let us try on a few different values:>>> round(4.5) 4 >>> round(3.5) 4 >>> round(1.75, 1) 1.8 >>> round(1.65, 1) 1.6The Decimal ClassThe  decimal module in Python is one of those features of the language which you might not be aware of if you have just started learning Python. Decimal “is based on a floating-point model which was designed with people in mind, and necessarily has a paramount guiding principle – computers must provide an arithmetic that works in the same way as the arithmetic that people learn at school.” – except from the decimal arithmetic specification. Some of the benefits of the decimal module are mentioned below -Exact decimal representation: 0.1 is actually 0.1, and 0.1 + 0.1 + 0.1 - 0.3 returns 0, as expected.Preservation of significant digits: When you add 1.50 and 2.30, the result is 3.80 with the trailing zero maintained to indicate significance.User-alterable precision: The default precision of the decimal module is twenty-eight digits, but this value can be altered by the user to match the problem at hand.Let us see how rounding works in the decimal module.>>> import decimal >>> decimal.getcontext() Context(     prec=28,     rounding=ROUND_HALF_EVEN,     Emin=-999999,     Emax=999999,     capitals=1,     clamp=0,     flags=[],     traps=[         InvalidOperation,         DivisionByZero,         Overflow     ] )The function decimal.getcontext() returns a context object which represents the default context of the decimal module. It also includes the default precision and the default rounding strategy.In the above example, you will see that the default rounding strategy for the decimal module is ROUND_HALF_EVEN. It allows to align with the built-in round() functionLet us create a new Decimal instance by passing a string containing the desired value and declare a number using the decimal module’s Decimal class.>>> from decimal import Decimal >>> Decimal("0.1") Decimal('0.1')You may create a Decimal instance from a floating-point number but in that case, a floating-point representation error will be introduced. For example, this is what happens when you create a Decimal instance from the floating-point number 0.1>>> Decimal(0.1) Decimal('0.1000000000000000055511151231257827021181583404541015625')You may create Decimal instances from strings containing the decimal numbers you need in order to maintain exact precision.Rounding a Decimal using the .quantize() method:>>> Decimal("1.85").quantize(Decimal("1.0")) Decimal('1.8')The Decimal("1.0") argument in .quantize() allows to determine the number of decimal places in order to round the number. As 1.0 has one decimal place, the number 1.85 rounds to a single decimal place. Rounding half to even is the default strategy, hence the result is 1.8.Decimal class:>>> Decimal("2.775").quantize(Decimal("1.00")) Decimal('2.78')Decimal module provides another benefit. After performing arithmetic the rounding is taken care of automatically and also the significant digits are preserved.>>> decimal.getcontext().prec = 2 >>> Decimal("2.23") + Decimal("1.12") Decimal('3.4')To change the default rounding strategy, you can set the decimal.getcontect().rounding property to any one of several  flags. The following table summarizes these flags and which rounding strategy they implement:FlagRounding Strategydecimal.ROUND_CEILINGRounding updecimal.ROUND_FLOORRounding downdecimal.ROUND_DOWNTruncationdecimal.ROUND_UPRounding away from zerodecimal.ROUND_HALF_UPRounding half away from zerodecimal.ROUND_HALF_DOWNRounding half towards zerodecimal.ROUND_HALF_EVENRounding half to evendecimal.ROUND_05UPRounding up and rounding towards zeroRounding NumPy ArraysIn Data Science and scientific computation, most of the times we store data as a  NumPy array. One of the most powerful features of NumPy is the use of  vectorization and broadcasting to apply operations to an entire array at once instead of one element at a time.Let’s generate some data by creating a 3×4 NumPy array of pseudo-random numbers:>>> import numpy as np >>> np.random.seed(444) >>> data = np.random.randn(3, 4) >>> data array([[ 0.35743992,  0.3775384 ,  1.38233789,  1.17554883],        [-0.9392757 , -1.14315015, -0.54243951, -0.54870808], [ 0.20851975, 0.21268956, 1.26802054, -0.80730293]])Here, first we seed the np.random module to reproduce the output easily. Then a 3×4 NumPy array of floating-point numbers is created with np.random.randn().Do not forget to install pip3 before executing the code mentioned above. If you are using  Anaconda you are good to go.To round all of the values in the data array, pass data as the argument to the  np.around() function. The desired number of decimal places is set with the decimals keyword argument. In this case, round half to even strategy is used similar to Python’s built-in round() function.To round the data in your array to integers, NumPy offers several options which are mentioned below:numpy.ceil()numpy.floor()numpy.trunc()numpy.rint()The np.ceil() function rounds every value in the array to the nearest integer greater than or equal to the original value:>>> np.ceil(data) array([[ 1.,  1.,  2.,  2.],        [-0., -1., -0., -0.], [ 1., 1., 2., -0.]])Look at the code carefully, we have a new number! Negative zero! Let us now take a look at Pandas library, widely used in Data Science with Python.Rounding Pandas Series and DataFramePandas has been a game-changer for data analytics and data science. The two main data structures in Pandas are Dataframe and Series. Dataframe works like an Excel spreadsheet whereas you can consider Series to be columns in a spreadsheet. Series.round() and DataFrame.round() methods. Let us look at an example.Do not forget to install pip3 before executing the code mentioned above. If you are using  Anaconda you are good to go.>>> import pandas as pd >>> # Re-seed np.random if you closed your REPL since the last example >>> np.random.seed(444) >>> series = pd.Series(np.random.randn(4)) >>> series 0    0.357440 1    0.377538 2    1.382338 3    1.175549 dtype: float64 >>> series.round(2) 0    0.36 1    0.38 2    1.38 3    1.18 dtype: float64 >>> df = pd.DataFrame(np.random.randn(3, 3), columns=["A", "B", "C"]) >>> df           A         B         C 0 -0.939276 -1.143150 -0.542440 1 -0.548708  0.208520  0.212690 2  1.268021 -0.807303 -3.303072 >>> df.round(3)        A      B      C 0 -0.939 -1.143 -0.542 1 -0.549  0.209  0.213 2  1.268 -0.807 -3.303 The DataFrame.round() method can also accept a dictionary or a Series, to specify a different precision for each column. For instance, the following examples show how to round the first column of df to one decimal place, the second to two, and the third to three decimal places: >>> # Specify column-by-column precision with a dictionary >>> df.round({"A": 1, "B": 2, "C": 3})      A     B      C 0 -0.9 -1.14 -0.542 1 -0.5  0.21  0.213 2  1.3 -0.81 -3.303 >>> # Specify column-by-column precision with a Series >>> decimals = pd.Series([1, 2, 3], index=["A", "B", "C"]) >>> df.round(decimals)      A     B      C 0 -0.9 -1.14 -0.542 1 -0.5  0.21  0.213 2  1.3 -0.81 -3.303 If you need more rounding flexibility, you can apply NumPy's floor(), ceil(), and print() functions to Pandas Series and DataFrame objects: >>> np.floor(df)      A    B    C 0 -1.0 -2.0 -1.0 1 -1.0  0.0  0.0 2  1.0 -1.0 -4.0 >>> np.ceil(df)      A    B    C 0 -0.0 -1.0 -0.0 1 -0.0  1.0  1.0 2  2.0 -0.0 -3.0 >>> np.rint(df)      A    B    C 0 -1.0 -1.0 -1.0 1 -1.0  0.0  0.0 2  1.0 -1.0 -3.0 The modified round_half_up() function from the previous section will also work here: >>> round_half_up(df, decimals=2)       A     B     C 0 -0.94 -1.14 -0.54 1 -0.55  0.21  0.21 2 1.27 -0.81 -3.30Best Practices and ApplicationsNow that you have come across most of the rounding techniques, let us learn some of the best practices to make sure we round numbers in the correct way.Generate More Data and Round LaterSuppose you are dealing with a large set of data, storage can be a problem at times. For example, in an industrial oven you would want to measure the temperature every ten seconds accurate to eight decimal places, using a temperature sensor. These readings will help to avoid large fluctuations which may lead to failure of any heating element or components. We can write a Python script to compare the readings and check for large fluctuations.There will be a large number of readings as they are being recorded each and everyday. You may consider to maintain three decimal places of precision. But again, removing too much precision may result in a change in the calculation. However, if you have enough space, you can easily store the entire data at full precision. With less storage, it is always better to store at least two or three decimal places of precision which are required for calculation.In the end, once you are done computing the daily average of the temperature, you may calculate it to the maximum precision available and finally round the result.Currency Exchange and RegulationsWhenever we purchase an item from a particular place, the tax amount paid against the amount of the item depends largely on geographical factors. An item which costs you $2 may cost you less (say$1.8)  if you buy the same item from a different state. It is due to regulations set forth by the local government.In another case, when the minimum unit of currency at the accounting level in a country is smaller than the lowest unit of physical currency, Swedish rounding is done. You can find a list of such rounding methods used by various countries if you look up on the internet.If you want to design any such software for calculating currencies, keep in mind to check the local laws and regulations applicable in your present location.Reduce errorAs you are rounding numbers in a large datasets used in complex computations, your primary concern should be to limit the growth of the error due to rounding.SummaryIn this article we have seen a few methods to round numbers, out of those “rounding half to even” strategy minimizes rounding bias the best. We are lucky to have Python, NumPy, and Pandas already have built-in rounding functions to use this strategy. Here, we have learned about -Several rounding strategies, and how to implement in pure Python.Every rounding strategy inherently introduces a rounding bias, and the “rounding half to even” strategy mitigates this bias well, most of the time.You can round NumPy arrays and Pandas Series and DataFrame objects.If you enjoyed reading this article and found it to be interesting, leave a comment. To learn more about rounding numbers and other features of Python, join our Python certification course.
Rated 5.0/5 based on 43 customer reviews
13222
How to Round Numbers in Python

While you are dealing with data, sometimes you may... Read More

## What are Python KeyError Exceptions and How to Handle Them

Rated 4.5/5 based on 1 customer reviews
7939
What are Python KeyError Exceptions and How to Han...

There are times when you have written your code bu... Read More