Python实现字符串转NumPy浮点数组的工具函数
本文介绍了一个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浮点数组工具的介绍即全部内容,旨在为读者提供参考,欢迎支持。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









