unsupported format string passed to numpy.ndarray.__format__

Viewed 1563

I have array numpy

 a = array([[1.31927e-34],
           [5.46819e-38],
           [5.08072e-38],
           [5.07986e-35],
           [1.30973e-34],
           [1.99656e-34]], dtype=float32)

when I try to convert to float

for ele in a:
     float("{:.5f}".format(ele))

my error unsupported format string passed to numpy.ndarray.format. Pls help me.

1 Answers

I think the problem is your list is nested, i.e. 2D list. If we flatten it first (converting to 1D), then we can apply float() function on each element.

import numpy as np

a = np.array([[1.31927e-34],
              [5.46819e-38],
              [5.08072e-38],
              [5.07986e-35],
              [1.30973e-34],
              [1.99656e-34]], dtype='float32')

a_flatten = a.reshape(-1)

print(a_flatten)
[1.31927e-34 5.46819e-38 5.08072e-38 5.07986e-35 1.30973e-34 1.99656e-34]

for ele in a:
    print("{:.5f}".format(float(ele)))

0.00000
0.00000
0.00000
0.00000
0.00000
0.00000

They all end up being 0.00000 since they are way too small for us to represent in 5 decimals.

Related