Python实现字符串转NumPy浮点数组的工具函数

陈默
陈默
发布时间:2026-10-13| 5人浏览过
原创

本文介绍了一个Python工具函数,用于将包含空格、特殊符号及注释的字符串转换为NumPy浮点数组。该函数通过正则表达式清理非数字字符,移除注释行,并处理小数点与科学计数法符号,最终返回一维数组。此外,还简要补充了使用astype()将浮点型转换为整型的方法,为数据预处理提供实用参考。

字符串转NumPy数组工具函数原理

该工具支持解析由空格、美元符号($)或星号(*)等字符分隔的数字字符串,且能够正确处理包含小数点的数值格式。

核心调用方式为:NumArray=str2num(LineString,comment='#')。

函数内部逻辑首先会将字符串中所有非双精度浮点型(Double)相关的字符统一替换为空格,以标准化数据格式。

同时,函数会识别以井号(#)开头的注释内容,并将其及行尾剩余部分清空,确保仅保留有效数据。

经过上述处理后,函数最终返回一个一维的numpy.array数组对象。

str2num函数代码实现


import numpy
import scipy
def str2num(LineString,comment='#'):
 
  from io import StringIO as StringIO
  import re,numpy
 
  NumArray=numpy.empty([0],numpy.int16)
  NumStr=LineString.strip()
  #~ ignore comment string
  for cmt in comment:

    CmtRe=cmt+'.*$'
    NumStr=re.sub(CmtRe, " ", NumStr.strip(), count=0, flags=re.IGNORECASE)
 
  #~ delete all non-number characters,replaced by blankspace.
  NumStr=re.sub('[^0-9.e+-]', " ", NumStr, count=0, flags=re.IGNORECASE)
 
  #~ Remove incorrect combining-characters for double type.
  NumStr=re.sub('[.e+-](?=\s)', " ", NumStr.strip(), count=0, flags=re.IGNORECASE)
  NumStr=re.sub('[.e+-](?=\s)', " ", NumStr.strip(), count=0, flags=re.IGNORECASE)
  NumStr=re.sub('[e+-]$', " ", NumStr.strip(), count=0, flags=re.IGNORECASE)
  NumStr=re.sub('[e+-]$', " ", NumStr.strip(), count=0, flags=re.IGNORECASE)
 
  if len(NumStr.strip())>0:
    StrIOds=StringIO(NumStr.strip())
    NumArray= numpy.genfromtxt(StrIOds)
 
  return NumArray


if __name__ == "__main__":
  str = input("Enter your input: ");
  donser=str2num(str)
  print(donser)

浮点型转整型的补充方法

补充知识:在Python中,若需将NumPy数组从浮点型转换为整型,可采用特定方法。

具体实现是使用numpy库提供的astype()方法,例如代码示例所示。

以上关于Python字符串转NumPy浮点数组工具的介绍即全部内容,旨在为读者提供参考,欢迎支持。

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。