
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Round Elements of the Array to Nearest Integer in NumPy
To round elements of the array to the nearest integer, use the numpy.rint() method in Python Numpy. For values exactly halfway between rounded decimal values, NumPy rounds to the nearest even value.
The out is a location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
The condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.
Steps
At first, import the required library −
import numpy as np
Create an array with float type using the array() method −
arr = np.array([50.8, 120.3, 200.7, 320.1, 450.4, 500.6])
Display the array −
print("Array...
", arr)
Get the type of the array −
print("
Our Array type...
", arr.dtype)
Get the dimensions of the Array −
print("
Our Array Dimension...
",arr.ndim)
Get the shape of the Array −
print("
Our Array Shape...
",arr.shape)
To round elements of the array to the nearest integer, use the numpy.rint() method in Python Numpy. For values exactly halfway between rounded decimal values, NumPy rounds to the nearest even value −
print("
Result (rounded)...
",np.rint(arr))
Example
import numpy as np # Create an array with float type using the array() method arr = np.array([50.8, 120.3, 200.7, 320.1, 450.4, 500.6]) # Display the array print("Array...
", arr) # Get the type of the array print("
Our Array type...
", arr.dtype) # Get the dimensions of the Array print("
Our Array Dimension...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # To round elements of the array to the nearest integer, use the numpy.rint() method in Python Numpy # For values exactly halfway between rounded decimal values, NumPy rounds to the nearest even value. print("
Result (rounded)...
",np.rint(arr))
Output
Array... [ 50.8 120.3 200.7 320.1 450.4 500.6] Our Array type... float64 Our Array Dimension... 1 Our Array Shape... (6,) Result (rounded)... [ 51. 120. 201. 320. 450. 501.]