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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22557322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:09:39  来源:igfitidea点击:

numpy savetxt formatted as integer is not saving zeroes

pythonarrayscsvnumpy

提问by ziky90

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 上运行

采纳答案by askewchan

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

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

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

回答by Guto

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.0ffor the format of the output of the zeros.

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