python - ndarray array2string 输出格式
问题描述
我知道这是一个简单的问题,但只能在 SO 上找到部分答案,并且无法从 Python 或 Numpy 文档中弄清楚如何做。我确定它已记录在案,我只是不明白。
我需要使用固定格式(13.7e 的 6 个字段)打印/写入。我需要打印的数组可能有 4、8、12 或更多值。我发现np.array2string
,这几乎是我所需要的。
- 有没有办法消除前导和尾随
[
和]
? - 同样,有没有办法避免第二行和以下行的缩进?
解决方案不必使用array2string
。这是我发现控制ndarray
. 我愿意接受任何解决方案。:-)
这是我的一个简单示例,用于演示我想要的行为以及我得到的结果:
>>> import numpy as np
>>> foo = np.arange(4.0)
>>> # this shows desired output with 4 values
>>> print( ('%13.7e'*4) % (foo[0], foo[1], foo[2], foo[3]) )
0.0000000e+001.0000000e+002.0000000e+003.0000000e+00
>>> print ( np.array2string(foo, separator='', formatter={'float_kind':'{:13.7e}'.format}) )
[0.0000000e+001.0000000e+002.0000000e+003.0000000e+00]
>>> foo = np.arange(12.0)
>>> print ( np.array2string(foo, separator='', max_line_width=80, formatter={'float_kind':'{:13.7e}'.format}) )
[0.0000000e+001.0000000e+002.0000000e+003.0000000e+004.0000000e+005.0000000e+00
6.0000000e+007.0000000e+008.0000000e+009.0000000e+001.0000000e+011.1000000e+01]
>>> # this shows desired output with 12 values
>>> print( ('%13.7e'*6) % (foo[0], foo[1], foo[2], foo[3], foo[4], foo[5]) )
0.0000000e+001.0000000e+002.0000000e+003.0000000e+004.0000000e+005.0000000e+00
>>> print( ('%13.7e'*6) % (foo[6], foo[7], foo[8], foo[9], foo[10], foo[11]) )
6.0000000e+007.0000000e+008.0000000e+009.0000000e+001.0000000e+011.1000000e+01
解决方案
的输出np.array2string
只是一个字符串。您可以使用普通的字符串方法对其进行格式化。例如,您可以去掉前导/尾括号并使用以下命令替换空格:
foo = np.arange(12.)
s = (np.array2string(foo,
separator='',
formatter={'float_kind':'{:13.7e}'.format},
max_line_width=80).strip('[]').replace(' ', ''))
print(s)
# prints:
0.0000000e+001.0000000e+002.0000000e+003.0000000e+004.0000000e+005.0000000e+00
6.0000000e+007.0000000e+008.0000000e+009.0000000e+001.0000000e+011.1000000e+01
推荐阅读
- java - 如何测试从服务器拦截器设置的上下文键值
- swift - Swift 5.0:不推荐使用“withUnsafeBytes”:使用“withUnsafeBytes”
(...) - lua - Lua C - 体面的 LuaJIT 兼容方式,将错误抛出到恢复的协程中
- javascript - 如何根据响应 id 绑定 html 标签?
- javascript - 用另一个词替换 HTML 中第一次出现的所需词
- c++ - 获取通过 COM c++ 加载的 DLL 的版本信息
- java - stage.setIconify(true) 不适用于未装饰的舞台
- node.js - OCI 运行时执行失败:执行失败:container_linux.go:344:启动容器进程
- sql - 如何根据特定条件选择记录
- sql-server - Windows 任务计划程序未通过 .Net exe 连接到 SQL Server 数据库