这篇文章主要介绍了如何在python中把字符串转化成numpy浮点数组,此处通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考价值,需要的朋友可以参考下:
Python主要应用于:1、Web开发;2、数据科学研究;3、网络爬虫;4、嵌入式应用开发;5、游戏开发;6、桌面应用开发。
不同的数字之间使用 空格“ ”,“$”,"*"等隔开,支持带小数点的字符串
NumArray=str2num(LineString,comment='#')
将字符串中的所有非Double类型的字符全部替换成空格
以'#'开头直至行尾的内容被清空
返回一维numpy.array数组
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 array由浮点型转换为整型
——使用numpy中的astype()方法可以实现,如:
到此这篇关于如何在python中把字符串转化成numpy浮点数组的文章就介绍到这了,更多相关如何在python中把字符串转化成numpy浮点数组的内容请搜索亿速云以前的文章或继续浏览下面的相关文章希望大家以后多多支持亿速云!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。