繁体   English   中英

将包含括号和数字的字符串转换为浮点数组

[英]Convert a string containing brackets and numbers to an array of floats

如何将以下字符串转换为浮点数的 numpy 数组

'[[1.45757244e+03 0.00000000e+00 1.21294569e+03]
 [0.00000000e+00 1.45752223e+03 1.00732059e+03]
 [0.00000000e+00 0.00000000e+00 1.00000000e+00]]'

这是一种方法,但它无法拆分连续的“[”以使 cols 变量

def str2num(str_in, np_type, shape):
    names_list = str_in.splitlines()
    tem = []
    for row in names_list:
        is_str = isinstance(row, str)
        if is_str:
            cols = [s for s in row.split(string.whitespace+'[], ') if s]
            for col in cols:
                tem.append(col)
    tem = flatten(tem)
    return np.array(tem, dtype=np_type).reshape(shape)

如果您将字符串中的空格替换为逗号,则您将拥有一个可以使用json.loads读取的有效 JSON 字符串:

import json
import numpy as np
 
s = '''
[[1.45757244e+03 0.00000000e+00 1.21294569e+03]
 [0.00000000e+00 1.45752223e+03 1.00732059e+03]
 [0.00000000e+00 0.00000000e+00 1.00000000e+00]]
'''
 
a = np.array(json.loads(s.replace(' ', ',')), dtype=float)
print(a)

输出:

[[1.45757244e+03 0.00000000e+00 1.21294569e+03]
 [0.00000000e+00 1.45752223e+03 1.00732059e+03]
 [0.00000000e+00 0.00000000e+00 1.00000000e+00]]

这是另一种方法

def str2num(str_in, np_type, shape):
    names_list = str_in.splitlines()
    tem = []
    for row in names_list:
        is_str = isinstance(row, str)
        if is_str:
            cols = [s for s in row.split() if s]
            cols = [s.replace('[', '').replace(']', '') for s in cols]
            for col in cols:
                tem.append(col)
    tem = flatten(tem)
    return np.array(tem, dtype=np_type).reshape(shape)

str_in = '''
[[1.45757244e+03 0.00000000e+00 1.21294569e+03]
 [0.00000000e+00 1.45752223e+03 1.00732059e+03]
 [0.00000000e+00 0.00000000e+00 1.00000000e+00]]
'''
 
np_type = np.float
shape = (3, 3)
a = str2num(str_in, np_type, shape)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM