python - 用科学数字读取一行(如 0.4E-03)
问题描述
我想用 Python 处理文件中的以下行(Fortran 程序的输出):
74 0.4131493371345440E-03 -0.4592776407685850E-03 -0.1725046324754540
并获得一个数组,例如:
[74,0.4131493371345440e-3,-0.4592776407685850E-03,-0.1725046324754540]
我以前的尝试不起作用。特别是,如果我执行以下操作:
with open(filename,"r") as myfile:
line=np.array(re.findall(r"[-+]?\d*\.*\d+",myfile.readline())).astype(float)
我有以下错误:
ValueError: could not convert string to float: 'E-03'
解决方案
@ant.kr 这是一个可能的解决方案:
# Initial data
a = "74 0.4131493371345440E-03 -0.4592776407685850E-03 -0.1725046324754540 \n"
# Given the structure of the initial data, we can proceed as follow:
# - split the initial at each white space; this will produce **list** with the last
# the element being **\n**
# - we can now convert each list element into a floating point data, store them in a
# numpy array.
line = np.array([float(i) for i in a.split(" ")[:-1]])
推荐阅读
- pine-script - Pinescript:如何检查每支蜡烛在过去 14 天内是否发生了特定情况?
- java - 为什么这个使用 HashMap 的 Java 代码会导致 NullPointerException?
- r - 如何将字符转换为数字
- apache-spark - PySpark 的 Regexp_replace 解释
- db2 - 在 Db2 v11.1 上,如果在下班工作时间出现任何挂起或缓慢的情况,我们如何获取或设置 DBA 团队的通知?
- python - 如果在 Pandas 数据框中的组内满足条件,则更改列中的所有值
- django - 如何导航到 DJango 模板中呈现的 VueJ 中的不同路线
- c# - 在 C# 中打印 PDF 文件的更快方法
- r - 如何在 R 中创建一个 IF 语句来修剪单元格的最后一个字符
- data-cleaning - DQS 清理 SSIS 任务性能问题