numpy数组的格式化输出

时间:2016-02-18 19:31:29

标签: python numpy format

我有两个(numpy)数组,我想写入文件。第一个是长度为n的整数的1-d数组,第二个是尺寸为nx3的2-d数组。输出应根据(I8,TR5,3E14.6)格式化TR5 =插入5个空格。我可以通过遍历所有n个元素的循环来做到这一点,但这不会感觉到pythonic。我试过numpy.savetxt()。它只适用于2-d数组,但我无法理解如何包含整数和空白。有什么建议吗?

import numpy as np

fout = "outfile.txt"

coord = np.array([[0.0,0.0,0.0],[1.0,1.0,1.0],[2.0,2.0,2.0]],float)
nodnr = np.array([[1,2,3]],int)

np.savetxt(fout,coord,delimiter=" ",fmt="%14.6E")

输出应如下所示:

       1      0.000000E+00   0.000000E+00   0.000000E+00
       2      1.000000E+00   1.000000E+00   1.000000E+00
       3      2.000000E+00   2.000000E+00   2.000000E+00

1 个答案:

答案 0 :(得分:0)

将两个数组合并为一个dtype float

数组
arr = np.column_stack([nodnr.T, coord])

然后使用multi-format string

致电np.savetxt
import numpy as np

fout = "outfile.txt"

coord = np.array([[0.0,0.0,0.0],[1.0,1.0,1.0],[2.0,2.0,2.0]],float)
nodnr = np.array([[1,2,3]],int)
arr = np.column_stack([nodnr.T, coord])
np.savetxt(fout, arr, 
           fmt='{}{}{}'.format('%d', ' '*5, ' '.join(['%14.6E']*coord.shape[1])))

产量

1       0.000000E+00       0.000000E+00       0.000000E+00
2       1.000000E+00       1.000000E+00       1.000000E+00
3       2.000000E+00       2.000000E+00       2.000000E+00