How to print only 3 decimal places in python numpy array?
The Correct Answer and Explanation is :
To print only three decimal places in a NumPy array, you can use the numpy.set_printoptions() function, which allows you to configure how floating-point numbers are displayed. This can be particularly useful for improving the readability of your output, especially when dealing with large arrays or when the precision of the numbers isn’t necessary for your specific application.
Here’s how you can do it:
Example Code
import numpy as np
# Create a NumPy array with floating-point numbers
array = np.array([1.234567, 2.345678, 3.456789, 4.567890, 5.678901])
# Set the print options to display only 3 decimal places
np.set_printoptions(precision=3, suppress=True)
# Print the array
print(array)
Explanation
- Importing NumPy: First, we need to import the NumPy library, which is a fundamental package for scientific computing in Python. It provides support for arrays, matrices, and many mathematical functions.
- Creating an Array: We create a NumPy array containing floating-point numbers. This array can be generated from lists, tuples, or other arrays, and it can include any number of dimensions.
- Setting Print Options: The
numpy.set_printoptions()function allows you to customize how NumPy arrays are displayed.
- The
precisionparameter specifies the number of decimal places to display. By setting this to3, any floating-point numbers will be printed with three decimal places. - The
suppressparameter, when set toTrue, prevents NumPy from using scientific notation for small numbers, making the output cleaner and easier to read, especially when working with values close to zero.
- Printing the Array: Finally, we print the array. The output will display each element rounded to three decimal places, providing a clearer view of the data without unnecessary precision.
This method ensures that the formatting is applied consistently across the entire array, making it easy to manage the display of numerical data in scientific computations or data analysis.