我会很感激一些帮助。这是我的代码:
#! /usr/bin/python
import sys
import numpy as np
x = np.array(['aaa', 'bbb', 'ccc'])
y = np.array([10.0, 15.0, 25.0])
records_array = np.core.records.fromarrays([x, y])
np.savetxt(sys.stdout, records_array, fmt='%s %.1f')
给出(如预期):
aaa 10.0
bbb 15.0
ccc 25.0
为了将最后一列打印为百分比,我将最后一行更改为:
np.savetxt(sys.stdout, records_array, fmt='%s %.1f %%')
但得到以下错误信息:
File "./savetxt_percent.py", line 9, in <module>
np.savetxt(sys.stdout, records_array, fmt='%s %.1f %%')
File "/usr/local/lib/python2.7/dist-packages/numpy/lib/npyio.py", line 1055, in savetxt
raise error
ValueError: fmt has wrong number of % formats: %s %.1f %%
谢谢!
请您参考如下方法:
奇怪的是 % 没有得到正确的解释。当您为 fmt 使用字符串时,它必须解析它。我没有仔细查看代码,但在尝试将字符串拆分为“%”字符以计算要打印的数量时,它一定会感到困惑。要解决此问题,还可以将 np.savetxt 的 fmt 参数指定为预拆分列表。换句话说,你可以使用
np.savetxt(sys.stdout, records_array, fmt=['%s', '%.1f %%'])
这将适用于您希望输出中的任何数量/位置的“%”。
