【问题标题】:Convert a string containing brackets and numbers to an array of floats将包含括号和数字的字符串转换为浮点数组
【发布时间】:2021-03-05 15:57:32
【问题描述】:

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

【问题讨论】:

  • 哎呀!你是怎么得到的?数组的打印字符串是为转换回来而设计的。缺少逗号意味着它不能被评估为一个列表(列表)。并且 [] 妨碍了在空白处简单分割。
  • 伟大的 cmets,也许我应该用逗号替换东西,甚至将其转换为用逗号分隔的字符串列表。我会将我的代码添加到问题中。我把代码省略了,因为我不确定我是否走在正确的道路上。
  • 这种情况最常出现的上下文是在加载一个 pandas 数据框 csv ,该数据框在单个单元格中具有数组。 pandas 只能将str(array) 写入csv,然后将其作为字符串加载。

标签: python arrays string numpy


【解决方案1】:

如果您将字符串中的空格替换为逗号,那么您将获得一个有效的 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]]

【讨论】:

  • 我将使用您的答案,但会在下面添加我的答案,这比您实现的要困难得多。谢谢。
【解决方案2】:

这是另一种方法

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-25
    • 2015-01-03
    • 2020-04-13
    • 2018-11-02
    • 1970-01-01
    相关资源
    最近更新 更多