NumPy: Set the display format for ndarray

Posted: | Tags: Python, NumPy

The display format of NumPy array (ndarray) with print(), such as the number of decimal places, scientific notation, zero-padding, etc., can be changed using numpy.set_printoptions().

The settings configured with np.set_printoptions() only affect the display format when using print() and do not change the values of the original ndarray.

This article explains the following contents.

  • The current settings: np.get_printoptions()
  • The number of decimal places: precision, floatmode
  • Scientific notations: suppress
  • Custom formats for each data type: formatter

Using np.set_printoptions(), you can also configure whether to truncate the ndarray when it has many elements. Refer to the following article:

The current settings: np.get_printoptions()

You can check the current settings with np.get_printoptions(), which returns parameter values in a dictionary (dict) format.

import numpy as np

print(np.get_printoptions())
# {'edgeitems': 3, 'threshold': 1000, 'floatmode': 'maxprec', 'precision': 8, 'suppress': False, 'linewidth': 75, 'nanstr': 'nan', 'infstr': 'inf', 'sign': '-', 'formatter': None, 'legacy': False}

The number of decimal places: precision, floatmode

precision

You can specify the number of decimal places with the precision parameter.

precision is a setting for the number of decimal places, not significant figures. It does not affect the integer part.

By default, the value of precision is set to 8.

a = np.array([12.3456, 0.123456789])
print(a)
# [12.3456      0.12345679]

np.set_printoptions(precision=3)
print(a)
# [12.346  0.123]

np.set_printoptions(precision=10)
print(a)
# [12.3456       0.123456789]

floatmode

You can choose the display format for the decimal places with the floatmode parameter.

The default setting is floatmode=maxprec, where the number of decimal places for all elements is determined by the value of precision, but trailing zeros are not padded.

np.set_printoptions(precision=4, floatmode='maxprec')
print(a)
# [12.3456  0.1235]

np.set_printoptions(precision=10, floatmode='maxprec')
print(a)
# [12.3456       0.123456789]

With floatmode=fixed, all elements have a fixed number of decimal places based on precision, and trailing zeros are padded.

np.set_printoptions(precision=4, floatmode='fixed')
print(a)
# [12.3456  0.1235]

np.set_printoptions(precision=10, floatmode='fixed')
print(a)
# [12.3456000000  0.1234567890]

With floatmode=maxprec_equal, elements with fewer decimal places are padded with zeros to match the element that has the maximum number of decimal places.

np.set_printoptions(precision=4, floatmode='maxprec_equal')
print(a)
# [12.3456  0.1235]

np.set_printoptions(precision=10, floatmode='maxprec_equal')
print(a)
# [12.345600000  0.123456789]

With floatmode=unique, each element is displayed with the necessary number of decimal places, regardless of the precision setting.

np.set_printoptions(precision=4, floatmode='unique')
print(a)
# [12.3456       0.123456789]

np.set_printoptions(precision=10, floatmode='unique')
print(a)
# [12.3456       0.123456789]

np.round()

As mentioned above, np.set_printoptions() settings only affect display format with print() and don't change the original ndarray values.

If you want to create a new ndarray rounded to a specific number of digits, use np.round().

In np.round(), the first argument is the target ndarray, and the second is the number of decimal places. If a negative value is specified for the number of decimal places, the values are rounded to the nearest integer.

b = np.round(a, 2)
print(b)
# [12.35  0.12]

b = np.round(a, -1)
print(b)
# [10.  0.]

b = np.round([1234.56, 123456.789], -2)
print(b)
# [  1200. 123500.]

Scientific notations: suppress

By default, ndarray is displayed in scientific notation if the minimum value is less than 1e-4 (=0.0001) or if the ratio of the maximum and minimum values is greater than 1e3 (=1000).

When in scientific notation, all elements are displayed in that format.

a = np.array([0.123456, 0.123456])
print(a)
# [0.123456 0.123456]

a = np.array([0.123456, 0.0000123456])
print(a)
# [1.23456e-01 1.23456e-05]

a = np.array([123.456, 0.0123456])
print(a)
# [1.23456e+02 1.23456e-02]

By setting the parameter suppress=True in np.set_printoptions(), you can disable scientific notation and display the values in decimal format. By default, suppress is set to False, meaning that scientific notation is enabled.

np.set_printoptions(suppress=True)
print(a)
# [123.456       0.0123456]

If you always want to display the values in scientific notation, use the formatter parameter described later.

For scientific notation, the precision and floatmode settings are applied to the mantissa part of the number.

np.set_printoptions(suppress=True, precision=2)
print(a)
# [123.46   0.01]

np.set_printoptions(suppress=False, precision=2)
print(a)
# [1.23e+02 1.23e-02]

np.set_printoptions(suppress=False, precision=8, floatmode='fixed')
print(a)
# [1.23456000e+02 1.23456000e-02]

Custom formats for each data type: formatter

In np.set_printoptions(), you can set the formatter parameter to a dictionary of functions to apply custom formatting to each data type, such as float and int.

The format() function is convenient for formatting numerical values. For more information about format(), refer to the following article:

For float, you can specify the number of decimal places with .2f or .8f, or use scientific notation and specify the number of decimal places in the mantissa part with .2e or .8e.

np.set_printoptions(precision=8, floatmode='maxprec', suppress=False)

a = np.array([123.456, 0.0123456])
print(a)
# [1.23456e+02 1.23456e-02]

np.set_printoptions(formatter={'float': '{:.2f}'.format})
print(a)
# [123.46 0.01]

np.set_printoptions(formatter={'float': '{:.8f}'.format})
print(a)
# [123.45600000 0.01234560]

np.set_printoptions(formatter={'float': '{:.2e}'.format})
print(a)
# [1.23e+02 1.23e-02]

np.set_printoptions(formatter={'float': '{:.8e}'.format})
print(a)
# [1.23456000e+02 1.23456000e-02]

For int, you can zero-pad with 08d, or display the number in binary with b, octal with o, or hexadecimal with x.

a = np.array([12, 1234])
print(a)
# [  12 1234]

np.set_printoptions(formatter={'int': '{:08d}'.format})
print(a)
# [00000012 00001234]

np.set_printoptions(formatter={'int': '{:b}'.format})
print(a)
# [1100 10011010010]

np.set_printoptions(formatter={'int': '{:o}'.format})
print(a)
# [14 2322]

np.set_printoptions(formatter={'int': '{:x}'.format})
print(a)
# [c 4d2]

You can also use string methods for custom formatting, such as converting NumPy strings (numpystr) to uppercase. Additionally, anonymous functions (lambda expressions) can be used for custom processing.

a = np.array(['One', 'Two'])
print(a)
# ['One' 'Two']

np.set_printoptions(formatter={'numpystr': str.upper})
print(a)
# [ONE TWO]

np.set_printoptions(formatter={'numpystr': lambda x: '***' + x + '***'})
print(a)
# [***One*** ***Two***]

You can specify all the settings for the formatter together in a dictionary format. To consistently use specific settings throughout your script, you can include these settings at the beginning of your code.

Note that the data types (dtype), such as float and int, are set for the ndarray, not for individual element. The formatter for the data type of ndarray is applied to all elements.

np.set_printoptions(formatter={'float': '{:0.8e}'.format, 'int': '{:08d}'.format})

a = np.array([12, 12.34])
print(a.dtype)
print(a)
# float64
# [1.20000000e+01 1.23400000e+01]

a = np.array([12, 123])
print(a.dtype)
print(a)
# int64
# [00000012 00000123]

Related Categories

Related Articles