19

Let's say I have the array:

import numpy as np
x = np.array([1.2334, 2.3455, 3.456], dtype=np.float32)

and want to print:

print('{:.2f}%'.format(x))

It gives me:

unsupported format string passed to numpy.ndarray.__format__
4
  • 2
    stackoverflow.com/questions/2891790/… Commented Oct 15, 2018 at 19:08
  • 2
    Hmm..The np.set_printoptions(precision=2) worked..I was wondering though why the above code doesn't work. Commented Oct 15, 2018 at 20:23
  • or as a string ('{:.2f} %'*len(x)).format(*x) yields '1.23 %2.35 %3.46 %' repeats the format string by the size of x, then starred x unravels to format. Commented Oct 16, 2018 at 3:22
  • 2
    The .format mechanism depends on what's been defined in the object's __format__ method. numpy developers haven't put much effort into expanding this beyond the basics ('!s' and '!r'). Note that your format string doesn't work for lists either. Commented Oct 17, 2018 at 7:19

2 Answers 2

14

If you still want format

list(map('{:.2f}%'.format,x))
Out[189]: ['1.23%', '2.35%', '3.46%']
Sign up to request clarification or add additional context in comments.

1 Comment

print("x=" + str(list(map('{:.2f}%'.format,x)))) That is, if you want to use "print" and combine text with "+", you must use str().
2

Try this:

x = np.array([1.2334, 2.3455, 3.456], dtype=np.float32)

x= list(map(lambda x :str(x) + '%',x.round(2)))
print(f'{x}')

It would print:

['1.23%', '2.35%', '3.46%']

Comments

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.