如何在txt文件上只写整数numpy 2D数组

时间:2015-08-27 11:37:53

标签: python numpy writefile

我知道如何使用numpy.savetxt()编写txt文件,但我无法使用整数来编写文件。我有以下代码:

new_picks = new_picks.astype(int)
np.savetxt(fname='newPicksData.txt', X=new_picks.astype(int))

这就是我得到的矩阵的样子:

2.900000000000000000e+01 3.290000000000000000e+02 1.000000000000000000e+00
4.300000000000000000e+01 1.080000000000000000e+02 1.000000000000000000e+00
4.300000000000000000e+01 1.950000000000000000e+02 1.000000000000000000e+00
5.600000000000000000e+01 1.510000000000000000e+02 1.000000000000000000e+00
5.600000000000000000e+01 9.700000000000000000e+01 1.000000000000000000e+00
7.000000000000000000e+01 2.840000000000000000e+02 1.000000000000000000e+00
3.500000000000000000e+01 3.170000000000000000e+02 1.000000000000000000e+00
5.400000000000000000e+01 2.110000000000000000e+02 1.000000000000000000e+00
6.400000000000000000e+01 1.180000000000000000e+02 1.000000000000000000e+00
5.400000000000000000e+01 3.700000000000000000e+01 1.000000000000000000e+00
1.300000000000000000e+01 1.950000000000000000e+02 1.000000000000000000e+00
1.300000000000000000e+01 1.680000000000000000e+02 1.000000000000000000e+00
1.300000000000000000e+01 2.780000000000000000e+02 1.000000000000000000e+00
4.900000000000000000e+01 2.200000000000000000e+01 1.000000000000000000e+00
4.900000000000000000e+01 1.040000000000000000e+02 1.000000000000000000e+00
4.900000000000000000e+01 7.500000000000000000e+01 1.000000000000000000e+00
5.400000000000000000e+01 2.610000000000000000e+02 1.000000000000000000e+00
5.400000000000000000e+01 2.600000000000000000e+02 1.000000000000000000e+00
5.400000000000000000e+01 1.150000000000000000e+02 1.000000000000000000e+00
5.400000000000000000e+01 5.400000000000000000e+01 1.000000000000000000e+00
1.300000000000000000e+01 5.400000000000000000e+01 1.000000000000000000e+00
4.900000000000000000e+01 5.400000000000000000e+01 1.000000000000000000e+00

我正在寻找的是这样的:

29 329 1
43 108 1
43 195 1
56 151 1
56 97 1

2 个答案:

答案 0 :(得分:4)

您必须在

中添加额外的参数
savetxt(fname='newPicksData.txt', X=new_picks.astype(int), fmt ='%.0f\n')

这只是实际数字的形成。

答案 1 :(得分:2)

您必须使用fmt参数单独指定格式,请参阅此处的文档http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html

您必须使用以下语法来获得所需内容:

np.savetxt(fname='newPicksData.txt', X=new_picks.astype(int),fmt="%i")

省略该参数,将其默认为fmt='%.18e',这正是您在问题中发布的输出中看到的内容。

此外,您真的需要代码中的astype(int)部分吗? np.savetext命令可以将字符串/双精度格式化为int,而无需自行更改数据。这可以通过下面的代码块来证明:

import numpy
x = numpy.array([1.3,2.1,3.9,4.2,5.5,6.1])
numpy.savetxt(fname='newPicksData.txt', X=x, fmt="%i")

列出的代码块然后产生以下文本文件:

1
2
3
4
5
6