Skip to main content
 首页 » 编程设计

python之以科学计数法将带有科学计数法的文本文件读取到 Pandas 数据框

2025年02月15日7mayingbao

有没有一种方法可以使 txt 文件中的科学记数法保持一致,并在将其读取到 pandas 数据帧后保持一致。

pd.read_csv(physio_files[1], sep="", header = None)

以上命令禁止使用科学记数法。

请您参考如下方法:

考虑数据框 df

df = pd.DataFrame(1000000., range(5), range(5)) 
print(df) 
 
           0          1          2          3          4 
0  1000000.0  1000000.0  1000000.0  1000000.0  1000000.0 
1  1000000.0  1000000.0  1000000.0  1000000.0  1000000.0 
2  1000000.0  1000000.0  1000000.0  1000000.0  1000000.0 
3  1000000.0  1000000.0  1000000.0  1000000.0  1000000.0 
4  1000000.0  1000000.0  1000000.0  1000000.0  1000000.0 

您可以使用 pandas 'displat.float_format' 选项控制格式。您还可以使用 pd.option_context

临时假设该选项的值

使用 '{:0.4e}'.format 作为您的自定义格式化程序。更改 4 以满足您的需要。

with pd.option_context('display.float_format', '{:0.4e}'.format): 
    print(df) 
 
           0          1          2          3          4 
0 1.0000e+06 1.0000e+06 1.0000e+06 1.0000e+06 1.0000e+06 
1 1.0000e+06 1.0000e+06 1.0000e+06 1.0000e+06 1.0000e+06 
2 1.0000e+06 1.0000e+06 1.0000e+06 1.0000e+06 1.0000e+06 
3 1.0000e+06 1.0000e+06 1.0000e+06 1.0000e+06 1.0000e+06 
4 1.0000e+06 1.0000e+06 1.0000e+06 1.0000e+06 1.0000e+06