numpy savetxt格式化为整数不保存零

时间:2022-08-01 21:22:22

I am trying to save numpy.array to .csv in the following way.

我试图通过以下方式将numpy.array保存到.csv。

with open("resultTR.csv", "wb") as f:
    f.write(b'ImageId,Label\n')
    numpy.savetxt(f, result, fmt='%i', delimiter=",")

result is numpy.array that consists of two columns, first column are indices (numbers 1 through n) and second column values from (0,9).

结果是numpy.array,它由两列组成,第一列是索引(数字1到n),第二列是(0,9)。

Unfortunately I have problem that whenever there is 0 in the second column then nothing is written to the resulting .csv file in the second column.

不幸的是我遇到的问题是,只要第二列中有0,就没有任何内容写入第二列中生成的.csv文件。

In other words first five rows of array looks like this:

换句话说,前五行数组如下所示:

[[  1.00000000e+00   2.00000000e+00]
 [  2.00000000e+00   0.00000000e+00]
 [  3.00000000e+00   9.00000000e+00]
 [  4.00000000e+00   9.00000000e+00]
 [  5.00000000e+00   3.00000000e+00]

And first five rows of .csv file like this:

前五行的.csv文件如下:

ImageId,Label
1,2
2
3,9
4,9
5,3

It looks to me like my code should work and thus not saving zeroes seems to me very weird. Does anyone have some idea what can possibly be wrong with my code for writing to .csv file?

它看起来像我的代码应该工作,因此不保存零似乎在我看来非常奇怪。有没有人知道我的代码写入.csv文件可能有什么问题?

EDIT:

编辑:

Just for compleetnes my python version is 2.7.2 and it's running on Mac OS X 10.9.2

仅仅为了完成我的python版本是2.7.2并且它在Mac OS X 10.9.2上运行

2 个解决方案

#1


22  

I would try saving the array as an int array, as in result.astype(int), or in full:

我会尝试将数组保存为int数组,如result.astype(int)或完整:

with open("resultTR.csv", "wb") as f:
    f.write(b'ImageId,Label\n')
    numpy.savetxt(f, result.astype(int), fmt='%i', delimiter=",")

#2


0  

Also had the same problem in a script using numpy.savetxt, but i could not use result.astype(int) as I had floats in another column.

在使用numpy.savetxt的脚本中也有同样的问题,但我不能使用result.astype(int),因为我在另一列中浮动。

Solved it using %5.0f for the format of the output of the zeros.

使用%5.0f解决了它的输出格式。

#1


22  

I would try saving the array as an int array, as in result.astype(int), or in full:

我会尝试将数组保存为int数组,如result.astype(int)或完整:

with open("resultTR.csv", "wb") as f:
    f.write(b'ImageId,Label\n')
    numpy.savetxt(f, result.astype(int), fmt='%i', delimiter=",")

#2


0  

Also had the same problem in a script using numpy.savetxt, but i could not use result.astype(int) as I had floats in another column.

在使用numpy.savetxt的脚本中也有同样的问题,但我不能使用result.astype(int),因为我在另一列中浮动。

Solved it using %5.0f for the format of the output of the zeros.

使用%5.0f解决了它的输出格式。