Floats in a structured NumPy array and formatting its own string using .format ()

Can someone tell me why this NumPy entry is causing Python style string formatting problems? All floats in the record throttle on "{:f}".format(record) .

Thank you for your help!

 In [334]: type(tmp) Out[334]: numpy.core.records.record In [335]: tmp Out[335]: ('XYZZ', 2001123, -23.823917388916016) In [336]: tmp.dtype Out[336]: dtype([('sta', '|S6'), ('ondate', '<i8'), ('lat', '<f4')]) # Some formatting works fine In [337]: '{0.sta:6.6s} {0.ondate:8d}'.format(tmp) Out[337]: 'XYZZ 2001123' # Any float has trouble In [338]: '{0.sta:6.6s} {0.ondate:8d} {0.lat:11.6f}'.format(tmp) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /Users/jkmacc/python/pisces/<ipython-input-338-e5f6bcc4f60f> 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' 
+4
source share
1 answer

This question was answered by the NumPy user mailing list in the section "Floats forced to string using" {: f}. Format ()? ":

It seems that np.int64 / 32 and np.str inherit their native Python __format__() , but np.float32 / 64 does not receive __builtin__.float.__format__() . This is not intuitive, but now I see why this works:

 In [8]: '{:6.6s} {:8d} {:11.6f}'.format(tmp.sta, tmp.ondate, float(tmp.lat)) Out[8]: 'XYZZ 2001123 -23.820000' 

Thanks!

-Jon

EDIT: np.float32 / int32 inherits from native Python types if , your system is 32-bit. The same goes for 64-bit. The mismatch will create the same problem as the original record.

0
source

Source: https://habr.com/ru/post/1484524/


All Articles