首页 > 解决方案 > 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

标签: pythonnumpynumpy-ndarray

解决方案


的输出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

推荐阅读