Explain Codes LogoExplain Codes Logo

Pretty-print a NumPy array without scientific notation and with given precision

python
prompt-engineering
functions
dataframe
Anton ShumikhinbyAnton Shumikhin·Nov 19, 2024
TLDR

To pretty-print a NumPy array, without scientific notation, and with a fixed precision, use the numpy.set_printoptions function. With suppress and formatter, here’s your recipe to cook a desired display output, spiced accross 8 decimal places:

import numpy as np # Whip up a random NumPy array array = np.random.random(5) # Spice it to taste using these print options for a non-scientific display, keep decimals up to 8 places np.set_printoptions(precision=8, suppress=True, formatter={'all': lambda x: f'{x:0.8f}'}) print(array) # Now, we are cooking!

Here, NumPy prints arrays with values formatted as floating-point numbers, exactly as we want them -- with exactly 8 decimal places and without scientific notation.

Tailoring your array's outfit: Precision and formatting

When it comes to precision and detail, you ought to dress your NumPy arrays to impress. Whether it's for the clarity of your scientific paper, the accuracy of your report, or just your personal flair, understanding how to manipulate array display properties is a catwalk to glory.

Button up to a fixed number of decimal places

For floating-point numbers, sometimes it's the little things that matter. You might need those trailing zeros to express the precision level. Use the formatter argument to keep it sharp:

np.set_printoptions(precision=3, formatter={'float_kind': '{:0.3f}'.format}) # Like a well-tailored suit, expresses the level of precision

Numbers will retain their decimals up to the defined precision. Imagine 1.200 rather than just 1.2.

Single-use array outfits with context managers

To avoid setting the global options, use the context manager numpy.printoptions. This is like your array's Sunday best: temporary and pristine:

with np.printoptions(precision=2, suppress=True): print(array) # Dressed to the nines in these print settings. # Returns back to casual everyday clothes after the with block.

This ensures the custom printing options only apply within the context's scope, stopping you from involuntarily setting the entire globe's outfit.

Fashioning context managers for past seasons (legacy versions)

If you're wearing the old version of NumPy v1.15 which lacks the np.printoptions function, you can always stitch your own ensemble with custom_printoptions:

from contextlib import contextmanager @contextmanager def custom_printoptions(*args, **kwargs): # Your personal styler! original_options = np.get_printoptions() # Safely preserves the original fashion statement np.set_printoptions(*args, **kwargs) # Works on the transformation try: yield finally: np.set_printoptions(**original_options) # Finally, reverts to the original style with custom_printoptions(precision=2, suppress=True): print(array) # Fashion show! Rocking the custom print.

With these scripts on your stylist's rack, you can mix and match the visual representation of NumPy arrays to your liking.

Setting up the stage: Visual configuration in action

Let's dig deeper into Visual Configuration, the backstage of a data display show. It’s about getting your props and settings ready to make your array data the star of the show.

Tailor-made formatting with list comprehension

If you want your individual array elements to strike a pose, forget the global options, and get sewing:

formatted_array = np.array([f'{x:.2f}' for x in array.flatten()]).reshape(array.shape) # One size does not fit all! print(formatted_array) # The star strutting down the catwalk

This way, every individual number in the array can have a unique style.

Costume changes with array2string

If you need full control over array element formatting, np.array2string is your backstage pass:

print(np.array2string(array, formatter={'float_kind': lambda x: f'{x:.2f}'}))

You can dictate the specific dressing rules according to the datatypes within the array. Who said you can't be the director of your own show?

DecimalFormat for special performances

In cases where standard floating-point representations refuse to go in costume as commanded, you might need to comply with a specific number format:

import decimal from decimal import Decimal decimal.getcontext().prec = 2 formatted_array = np.array([str(Decimal(str(x)).quantize(Decimal('1.00'))) for x in array]) # It's not disobedience. It's a method act! print(formatted_array)

Here, Python’s Decimal module enforces a particular precision or rounding behavior that standard floats can't. For a performance requiring financial, military-grade critical precision—this is your star!