开发者

writing "missing array values" to a file

import numpy as np

f1= "test_io.csv"
f2= "test_io2.csv"

array = np.genfromtxt(f1,delimi开发者_运维技巧ter=',',missing_values='NA', filling_values=1.e20)
np.savetxt(f2,array,delimiter=',')

#np.savetxt(f2,array,delimiter=', missing_values = 1.e20, filling_values='NA')

As suggested by the second "savetxt", I would like to be able to replace missing values that were read in by genfromtxt and replaced by filling values, with 'NA' when writing a file. The best method I can find is to convert each row in the array to an array of str, replace the "missing value", and write each row with csv writer. Is there a better way?


There isn't a built in way to do it, as it's usually easier to just roll your own, than it is to make a "one-size-fits-all" function meet your needs.

In your case, I wouldn't bother with the csv module. It's great when you need to read complex data in, but for something this simple, it's far easier to not use it.

missing, fill = 1.e20, "NA"
with open("test_io2.csv", 'w') as outfile:
    for row in array:
        line = ','.join([str(x) for x in row if x != missing else fill])
        outfile.write(line + '\n')

The usual caveats about testing equality of floating point numbers apply, of course. It might make more sense to do something like if x < 9e19 else fill instead. That will depend on your particular application, though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜