使用numpy提取数组中的变量精度
import numpy as np
import csv
data_points = np.genfromtxt('input_arrray.txt', dtype = None)
# dtype = None since the array contains numbers and strings
csvfile = "/home/User/Desktop/output_array.txt"
with open(csvfile, "w") as output:
writer = csv.writer(output, delimiter='\t')
for row in range(len(data_points)):
parameter = data_points[row][5]
writer.writerow([parameter])
我正在使用 numpy.genfromtxt
来加载一个数组。我从这个数组中提取一个变量,然后把它保存到另一个 .txt 文件里,但输出的结果会有很多多余的数字。
比如说,在 input_array
中的值是 0.33625
,但在 output_array.txt
中显示的却是 0.33624999999999999
。
为了解决这个问题,我使用了:
writer.writerow(['%1.5f' % parameter])
不过,我对结果并不满意。我的原始数组有1900行和38列。我想从这38列中提取10列。但是当我使用 '%2.5f%
参数时,我的数据没有对齐。
有没有其他方法可以解决这个问题呢?
1 个回答
0
你可以强制把原始数据保持为字符串:
data_points = np.gengromtxt('input_array.txt', dtype=str)
然后使用 np.savetxt
写入数据时,设置 fmt='%s'
,这样就可以避免把字符串转换成浮点数,从而导致的四舍五入错误:
np.savetxt('output.txt', data_points, fmt='%s')