[Numpy-discussion] floats coerced to string with "{:f}".format() ?

Maccarthy, Jonathan K jkmacc@lanl....
Thu Jun 6 14:48:15 CDT 2013


Hi everyone,

I've looked in the mailing list archives and with the googles, but haven't yet found any hints with this question...

I have a float field in a NumPy record that looks like it's being substituted as a string in the Python "{:f}".format() mini-language, thus throwing an error:


In [1]: tmp = np.rec.array([('XYZZ', 2001123, -23.82396)], dtype=np.dtype([('sta', '|S6'), ('ondate', '<i8'), ('lat', '<f4')]))[0]

In [2]: type(tmp)
Out[3]: numpy.core.records.record

In [3]: tmp
Out[3]: ('XYZZ', 2001123, -23.823917388916016)

In [4]: tmp.sta, tmp.ondate, tmp.lat
Out[4]: ('XYZZ', 2001123, -23.823917)

# strings and integers work
In [5]: '{0.sta:6.6s} {0.ondate:8d}'.format(tmp)
Out[5]: 'XYZZ    2001123'

# "lat" is a float, but it seems to be coerced to a string first, and failing
In [6]: '{0.sta:6.6s} {0.ondate:8d} {0.lat:11.6f}'.format(tmp)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/Users/jkmacc/<ipython-input-312-bff8066cfde8> in <module>()
----> 1 '{0.sta:6.6s} {0.ondate:8d} {0.lat:>11.6f}'.format(tmp)

ValueError: Unknown format code 'f' for object of type 'str'

# string formatting for doesn't fail
In [7]: '{0.sta:6.6s} {0.ondate:8d} {0.lat:>11.6s}'.format(tmp)
Out[7]: 'XYZZ    2001123      -23.82'


This also fails:

In [7]: "{:f}".format(np.array(3.2, dtype='f4'))
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/Users/jkmacc/<ipython-input-314-33119128e3e6> in <module>()
----> 1 "{:f}".format(np.array(3.2, dtype='f4'))

ValueError: Unknown format code 'f' for object of type 'str'



Does anyone understand what's happening?

Thanks for your help.

Best,
Jon


More information about the NumPy-Discussion mailing list