What is the set_printoptions() function from numpy in Python?
Overview
In Python, we use the set_printoptions() function to set the way floating-point number(s), array(s), and other NumPy objects are displayed.
Syntax
set_printoptions(precision=None, threshold=None, edgeitems=None, suppress=None)
Parameters
This function takes the following parameter values:
precision: This represents the number of digits of precision for floating-point output, which is optional, and the default value is8.threshold: This represents the total number of array elements that trigger summarization rather than fullrepr. This is optional with a default value of1000.edgeitems: This represents the number of array items in summary at the beginning and end of each dimension. This is optional and has a default value of3.suppress: This takes a Boolean value. IfTrue, the function will always print floating-point numbers using a fixed point notation. In this case, the numbers equal to zero in the current precision will print as zero. IfFalse, the scientific notation is used when the absolute value of the smallest is <1e-4 or the ratio of the maximum absolute value to the minimum is >1e3. This is optional and with a default value ofFalse.
Example
from numpy import set_printoptions, arange# setting the printing optionsset_printoptions(precision=4, threshold=5, edgeitems=3, suppress=True)# creating an array objectmyarray = arange(10)# printing the arayprint(myarray)
Explanation
- Line 1: We import
arangeandset_printoptionsfrom thenumpymodule. - Line 4: We implement the
set_printoptions()function using aprecisionvalue of4,thresholdvalue of5,edgeitemsvalue of3and thesuppressvalue asTrue. This sets the printing option of our code. - Line 7: We use the
arange()function to create an array objectmyarraywith integers from1to9. - Line 10: We print the array object
myarray.