Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python和从excel文件导入浮点数_Python_Excel_Pandas_Import_Floating - Fatal编程技术网

Python和从excel文件导入浮点数

Python和从excel文件导入浮点数,python,excel,pandas,import,floating,Python,Excel,Pandas,Import,Floating,我有一个excel文件,看起来像这样 Name R s l2 max_amplitude ref_amplitude R_0.3_s_0.5_l2_0.1 0.3 0.5 0.1 1.45131445 1.45131445 R_0.3_s_0.5_l2_0.6 0.3 0.5 0.6 3.52145743 3.52145743 ... R_1.1_s_2.0_l2_1.6 1.1 2.0 1.6 5.07415199 5.07

我有一个excel文件,看起来像这样

    Name    R   s   l2  max_amplitude   ref_amplitude
    R_0.3_s_0.5_l2_0.1  0.3 0.5 0.1 1.45131445  1.45131445
    R_0.3_s_0.5_l2_0.6  0.3 0.5 0.6 3.52145743  3.52145743
   ...
    R_1.1_s_2.0_l2_1.6  1.1 2.0 1.6 5.07415199  5.07415199
    R_1.1_s_2.0_l2_2.1  1.1 2.0 2.1 5.78820419  5.78820419
    R_1.1_s_2.0_l2_2.6  1.1 2.0 2.6 5.84488964  5.84488964
    R_1.1_s_2.0_l2_3.1  1.1 2.0 3.1 6.35387516  6.35387516
使用pandas模块,我将数据导入数据帧

import pandas as pd
df = pd.read_excel("output_var.xlsx", header=0)
一切似乎都很好:

df
在命令行中,生成:

       R    s   l2  max_amplitude  ref_amplitude
0    0.3  0.5  0.1       1.451314       1.451314
1    0.3  0.5  0.6       3.521457       3.521457
2    0.3  0.5  1.1       4.770226       4.770226
...
207  1.1  2.0  2.1       5.788204       5.788204
208  1.1  2.0  2.6       5.844890       5.844890
209  1.1  2.0  3.1       6.353875       6.353875

[210 rows x 5 columns]
现在我需要根据R的值做一些计算,所以我需要对数组进行切片。列R包含5个不同的值:0.3、0.5、0.7、0.9和1.1。这5个值中的每一个都有42行。(5x42=210) 要删除“R”中的重复项,我尝试

返回:

{0.29999999999999999,
 0.5,
 0.69999999999999996,
 0.89999999999999991,
 0.90000000000000002,
 1.1000000000000001}
除了将0.3表示为0.29999等之外,R还有6个(而不是5个)不同的值。有时,0.9被解释为0.8999999991,有时被解释为0.90000000000000002 这可以通过以下方法(部分)解决:

set(round(df.R,1))
其中(至少)返回5个值:

{0.29999999999999999,
 0.5,
 0.69999999999999996,
 0.90000000000000002,
 1.1000000000000001}
但现在我来谈谈危险的部分。如果我想根据已知的R值(0.3、0.5、0.7、0.9和1.1)进行切片

返回

42
41

返回

42
41
Python删除了一个值!(请记住,5个R中的每一个都有42行,表示文件中总共有210行)。
如何处理这个问题?

不要检查浮动是否相等。浮点运算存在一些问题(例如检查)

相反,请检查(非常接近):

通常,如果不将序列转换为集合,pandas将处理该问题。因此,如果您想删除重复项,我建议使用以下方法:

df.drop_duplicates('R')

感谢您的及时回复,但是pandas'drop_duplicates'并不能解决浮点问题:“df.R.drop_duplicates()”的结果是:“0.3 0.5 0.7 0.9 0.9 1.1”,所以我还有两个“不同的”0.9values@Mato您确定它们在Excel文件中是相同的吗?如果可能,您可以共享该文件(或其中的一部分)吗?在excel中,R=0.9的数据看起来完全相同,但我刚刚尝试将数据快速导入Mathematica,出现了相同的问题(两个0.9值)。因此,问题似乎出在数据中(尽管Excel文件是使用“to_Excel”命令生成的)。我将不得不在那里寻找问题。
import numpy as np
len(df[np.isclose(df.R, 0.9)])
df.drop_duplicates('R')