首页 > 解决方案 > 将包含括号和数字的字符串转换为浮点数组

问题描述

如何将以下字符串转换为 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)

标签: pythonarraysstringnumpy

解决方案


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

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]]

推荐阅读