Reputation: 781
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.
Upvotes: 5
Views: 5162
Reputation: 2273
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]
Upvotes: 4
Reputation: 215127
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]
Upvotes: 3