Formatting NumPy Arrays for Readable Output

When working with NumPy arrays, it’s often necessary to print them in a readable format, especially when dealing with floating-point numbers. By default, NumPy may display these numbers in scientific notation or with too many decimal places, making the output difficult to read. In this tutorial, we’ll explore how to format NumPy arrays for better readability.

Understanding the Problem

NumPy arrays are often printed using the print() function, which can lead to unreadable output due to the default formatting settings. For example:

import numpy as np

x = np.random.random(10)
print(x)

This may produce an output like:

[ 0.07837821  0.48002108  0.41274116  0.82993414  0.77610352  0.1023732
  0.51303098  0.4617183   0.33487207  0.71162095]

As you can see, the output is not very readable due to the excessive number of decimal places.

Using np.set_printoptions() for Global Formatting

To format NumPy arrays globally, you can use the np.set_printoptions() function. This function allows you to set various options, including precision and suppression of scientific notation.

import numpy as np

x = np.random.random(10)
np.set_printoptions(precision=3)
print(x)

This will produce an output like:

[ 0.078  0.480  0.413  0.830  0.776  0.102  0.513  0.462  0.335  0.712]

Note that the precision parameter sets the number of decimal places to display.

Suppressing Scientific Notation

To suppress scientific notation for small numbers, you can use the suppress parameter:

import numpy as np

y = np.array([1.5e-10, 1.5, 1500])
np.set_printoptions(suppress=True)
print(y)

This will produce an output like:

[    0.      1.5  1500. ]

Local Formatting with np.printoptions()

If you want to apply formatting options only locally, without changing the global settings, you can use the np.printoptions() context manager (available in NumPy 1.15 and later):

import numpy as np

x = np.random.random(10)
with np.printoptions(precision=3, suppress=True):
    print(x)

This will produce an output like:

[ 0.073  0.461  0.689  0.754  0.624  0.901  0.049  0.582  0.557  0.348]

Outside the with block, the global settings will be restored.

Formatting Individual Elements

If you want to format individual elements of a NumPy array, you can use the np.array_str() function:

import numpy as np

x = np.array([[1.1, 0.9, 1e-6]] * 3)
print(np.array_str(x, precision=2))

This will produce an output like:

[[  1.10e+00   9.00e-01   1.00e-06]
 [  1.10e+00   9.00e-01   1.00e-06]
 [  1.10e+00   9.00e-01   1.00e-06]]

Conclusion

In this tutorial, we’ve covered various ways to format NumPy arrays for better readability. By using np.set_printoptions(), np.printoptions(), and np.array_str(), you can control the output of your NumPy arrays and make them easier to read.

Leave a Reply

Your email address will not be published. Required fields are marked *