5

I want to print formatted numpy array along with a float with different significant figures. Consider the following code

a = 3.14159
X = np.array([1.123, 4.456, 7.789])
print('a = %4.3f, X = %3.2f' % (a, X))
------------------------
TypeError: only size-1 arrays can be converted to Python scalars

I desire following output-

a = 3.141, X = [1.12, 4.45, 7.78]

Suggest a modification in the code.

1
  • 1
    you can't apply scalar %f formating to a whole array. As with a list you have to iterate, applying it element by element. Commented Aug 3, 2021 at 17:33

2 Answers 2

4

You can use np.set_printoptions(precision=2):

import numpy as np
a = 3.14159
X = np.array([1.123, 4.456, 7.789])
np.set_printoptions(precision=2)
print(f'{a = :4.3f}, X = {X}')

Output

a = 3.142, X = [1.12 4.46 7.79]
Sign up to request clarification or add additional context in comments.

Comments

3

Convert array to string first with array2string:

print('a = %4.3f, X = %s' % (a, np.array2string(X, precision=2)))
# a = 3.142, X = [1.12 4.46 7.79]

2 Comments

this doesn't have the commas as indicated in the question.
@SOFe np.array2string(X, precision=2, separator=',') would give you the commas. See the separator option in numpy.org/doc/stable/reference/generated/….

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.