numpy - 使用 .format() 在 NumPy 结构化数组和原生字符串格式中 float

标签 numpy string-formatting record

谁能告诉我为什么这个 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/

相关文章:

python - 用 numpy 反转分数矩阵

sql-server - 未记录的 CONVERT 样式 - 日期时间 23

python - 在 python 中更改列表答案

c# - 添加用于填充字符串的参数 (C#)

haskell - 在 Haskell 中使用多态记录的意外缓存行为

python - 如何创建 numpy View 数组?

python - 为什么 np.astype ('uint8' ) 在 Windows 和 Mac 上给出不同的结果?

python - 迭代两个数组在字典中查找值

c++ - 如何使用 GStreamer 以编程方式创建视频(来自 RGB 和 PCM)?

delphi - 类型转换无效 : convert record to tobject on 64-bit platform