Explain Codes LogoExplain Codes Logo

How do I print the full NumPy array without truncation?

python
numpy
printoptions
data-structures
Anton ShumikhinbyAnton ShumikhinยทAug 17, 2024
โšกTLDR

Directly modify the print options for NumPy with numpy.set_printoptions and set threshold=sys.maxsize. This will print all elements of the array, no omission:

import numpy as np import sys np.set_printoptions(threshold=sys.maxsize) print(np.arange(1000)) # Prints 1000 integers because we're not falling for the "integer overflow" magic trick today! ๐Ÿ˜Ž

Bypassing truncation, context managers, and print functionality

Let's get into more fine-tuned control over printing arrays!

Convert array to list

Escape the bonds of NumPy's print rules by turning your array into a plain-old Python list:

print(your_array.tolist()) # Python lists might not have NumPy's sleek performance, but hey, no one truncates them! ๐Ÿ˜†

Use context managers

Need a once-off sneak peek of the full array without changing global settings? Utilize **np.printoptions **:

with np.printoptions(threshold=np.inf): print(your_array) # Context Manager a.k.a temporary parole from NumPy's print restrictions!

After this block, settings seamlessly revert to original. No strings attached!

Define fullprint function for frequent use

Encapsulate above within a function. This is handy when you find yourself needing to print full arrays frequently:

def fullprint(*args, **kwargs): with np.printoptions(threshold=np.inf): print(*args, **kwargs) # "Display all" function a.k.a your new favourite printing toy ๐Ÿงธ

Pretty print with pprint

When working with complex, multidimensional arrays, enlist the help of pprint:

from pprint import pprint pprint(your_array) # Who says programmers don't care about aesthetics?

Creating large scale testing arrays

Experiment your new-found print powers on larger arrays using **numpy.arange ** and reshape:

large_array = np.arange(10000).reshape(100,100) fullprint(large_array) # "Is this array large? Yes. Do we print it all anyway? Also yes!" ๐Ÿ˜…

Hands-on with printoptions parameters

NumPy's printoptions packs more tools than just threshold. For instance:

  • precision: controls decimal places for floating-point numbers.
  • suppress: toggle to display small numbers without scientific notation.
  • formatter: for advanced tweaks in how arrays are printed.