Format Python numpy array output

Question:

How do I get this code to always return 1 decimal for every element in the array?

import numpy as np

def mult_list_with_x(liste, skalar):
    print(np.array(liste) * skalar)

liste = [1, 1.5, 2, 2.5, 3]
skalar = 2

mult_list_with_x(liste, skalar)

I.e.:
[2.0 3.0 4.0 5.0 6.0]

not
[2. 3. 4. 5. 6.]

Asked By: Lars Moe

||

Answers:

You can use np.set_printoptions to set the format:

import numpy as np

def mult_list_with_x(liste, skalar):
    print(np.array(liste) * skalar)

liste = [1, 1.5, 2, 2.5, 3]
skalar = 2

np.set_printoptions(formatter={'float': '{: 0.1f}'.format})

mult_list_with_x(liste, skalar)

Output:

[ 2.0  3.0  4.0  5.0  6.0]

Note that this np printoptions setting is permanent – see below for a temporary option.
Or to reset the defaults afterwards use:

np.set_printoptions(formatter=None)
np.get_printoptions()  # to check the settings

An option to temporarily set the print options – kudos to mozway for the hint in the comments!:

with np.printoptions(formatter={'float': '{: 0.1f}'.format}):
    print(np.array(liste) * skalar)

An option to just format the print output as string:

print(["%.1f" % x for x in ( np.array(liste) * skalar)])

Output:

['2.0', '3.0', '4.0', '5.0', '6.0']

Choose an option fitting how the output should further be used.

Answered By: MagnusO_O

You need to use this setup first:

float_formatter = "{:.1f}".format
np.set_printoptions(formatter={'float_kind':float_formatter})

Output

[2.0 3.0 4.0 5.0 6.0]
Answered By: the_ordinary_guy
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.