谁能告诉我为什么这个 NumPy 记录在 Python 的新型字符串格式方面有问题?记录中的所有 float 都在 "{:f}".format(record)
上窒息.
谢谢你的帮助!
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'
最佳答案
这个问题在 NumPy 用户邮件列表中的“floats coerced to string with "{:f}".format() ?”下得到了回答:
似乎 np.int64/32 和 np.str 继承了各自的原生 Python __format__()
,但 np.float32/64 没有得到 __builtin__.float.__format__()
.这不直观,但我现在明白为什么这样做了:
In [8]: '{:6.6s} {:8d} {:11.6f}'.format(tmp.sta, tmp.ondate, float(tmp.lat))
Out[8]: 'XYZZ 2001123 -23.820000'
谢谢!
-乔恩
编辑 :
np.float32/int32 继承自 Python 原生类型 如果 你的系统是32位的。 64 位也一样。不匹配将产生与原始帖子相同的问题。
关于numpy - 使用 .format() 在 NumPy 结构化数组和原生字符串格式中 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16928644/