在 x 数组中使用 numpy.astype 时,如何将科学计数法转换为原始格式?这是我的代码:
with open ('outfile.csv', 'r') as infile:
reader = csv.reader(infile)
reader_list = list(reader)
reader_array = array(reader_list)
x = reader_array[:,5].astype(np.float)
#original array:
print reader_array[:,5]
#converted to float
print x
#original array:
['-0.00041955436132607246' '-0.00036612800229292086' '0.00022313364860991641' ..., '73.418371245304215' '73.417384428365267' '73.416718169781149']
#converted to float
[ -4.19554361e-04 -3.66128002e-04 2.23133649e-04 ..., 7.34183712e+01 7.34173844e+01 7.34167182e+01]
更具体地说,我想将字符串数组转换为 float ,但保持与原始数组相同的格式,并对其进行一些分析:
#find row number of max value in column 1: (This piece works fine)
max_index = where(reader_array[:,1] == max(reader_array[:,1]))
#take last element in column 5: (This one is also fine)
total_ = (reader_array[(len(reader_array[:,5])-1),5])
#find row number where element in column 5 is equal to 0.1*total_: (here's the problem!)
0.1_index = where((reader_array[:,5]) == (total_)*0.1)
所以我认为将字符串更改为 float 但使用与原始数组相同的格式允许将数组成员乘以另一个 float (此处为 0.1)。
请注意,值 (0.1*total_) 可能与第 5 列中的任何行值都不匹配,我必须考虑如何解决。但是如果不能将行与 (0.1*total_) 进行比较,我就无法取得进步。
如果有人可以提示如何处理,我将不胜感激。
最佳答案
您本质上受到 float 使用 IEEE 754 存储这一事实的限制。 .您不能拥有任意精度的 float ,因此在您的情况下,您不能期望它们一定与字符串表示形式完全相同。
但是,在您的情况下,更紧迫的问题是要将字符串与 float 进行比较,因此它们当然会有所不同。 Python 是动态的,但是 strongly打字。
鉴于以上两点,您需要更好地定义您的问题。为什么需要与字符串数组进行比较? (这是什么意思!?)
一旦您整理好数据类型(例如使用 numpy.close
),您能否测试接近度而不是相等性?
关于python - 将二维字符串数组转换为 python_removing 科学记数法中的 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20279013/