14

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__
ans
  • 378
  • 1
  • 5
  • 18
George
  • 5,808
  • 15
  • 83
  • 160
  • 1
    https://stackoverflow.com/questions/2891790/how-to-pretty-printing-a-numpy-array-without-scientific-notation-and-with-given – BENY Oct 15 '18 at 19:08
  • 1
    Hmm..The `np.set_printoptions(precision=2)` worked..I was wondering though why the above code doesn't work. – George Oct 15 '18 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. – NaN Oct 16 '18 at 03: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. – hpaulj Oct 17 '18 at 07:19

2 Answers2

13

If you still want format

list(map('{:.2f}%'.format,x))
Out[189]: ['1.23%', '2.35%', '3.46%']
BENY
  • 317,841
  • 20
  • 164
  • 234
  • `print("x=" + str(list(map('{:.2f}%'.format,x))))` That is, if you want to use "print" and combine text with "+", you must use str(). – Convexity May 27 '23 at 10:35
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%']
Aadil Rashid
  • 679
  • 6
  • 6