我有A号线.我想要转换为数组,但我面临错误.我介绍了当前和预期的输出.

import ast
import numpy as np

A = '\n[array([[[   0,   22],\n [   0,   23]]], dtype=int64)]'

# Remove unnecessary characters and fix dtype
A_cleaned = A.replace('\n', '').replace('dtype=int64', '').strip()

# Extract the content inside the outermost brackets
start_idx = A_cleaned.find('[')
end_idx = A_cleaned.rfind(']')
inner_list_str = A_cleaned[start_idx:end_idx+1]

# Replace 'array' with 'np.array'
inner_list_str = inner_list_str.replace('array', 'np.array')

# Use ast.literal_eval to safely evaluate the string as a Python literal
try:
    inner_list = ast.literal_eval(inner_list_str)
    np_array = np.array(inner_list)
    print("NumPy array:")
    print(np_array)
    print("Data type of np_array:", type(np_array))
except Exception as e:
    print(f"Error: Unable to convert the string to a NumPy array. {e}")

当前输出为

Error: Unable to convert the string to a NumPy array. malformed node or string on line 1: <ast.Call object at 0x000001709540B640>

预期yields 为

[array([[[   0,   22], [   0,   23]]])]

推荐答案

ast.literal_eval份文档中摘录:

计算表达式 node 或仅包含Python文本或容器显示的字符串.The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, None and Ellipsis.

这意味着你不能使用literal_eval来解析非原生类型,比如numpy.array.

以下是一些如何解决这个问题的建议:

  • use eval instead of ast.literal_eval
    (WARNING be careful as this might be harmful since string will be evaluated as python-code without any checks!!)
  • 也go 掉np.array部分,用ast.literal_eval将数据解析为list,然后将其转换为数字array.

Python相关问答推荐

将jit与numpy linSpace函数一起使用时出错

Pandas 有条件轮班操作

什么是最好的方法来切割一个相框到一个面具的第一个实例?

使用Python从URL下载Excel文件

在不同的帧B中判断帧A中的子字符串,每个帧的大小不同

OpenCV轮廓.很难找到给定图像的所需轮廓

根据客户端是否正在传输响应来更改基于Flask的API的行为

Python类型提示:对于一个可以迭代的变量,我应该使用什么?

使用python playwright从 Select 子菜单中 Select 值

在我融化极点数据帧之后,我如何在不添加索引的情况下将其旋转回其原始形式?

当输入是字典时,`pandas. concat`如何工作?

合并相似列表

如何从数据框列中提取特定部分并将该值填充到其他列中?

启动线程时,Python键盘模块冻结/不工作

如何在Pandas中用迭代器求一个序列的平均值?

根据过滤后的牛郎星图表中的数据计算新系列

使用pythonminidom过滤XML文件

如何在Polars中处理用户自定义函数的多行结果?

利用广播使减法更有效率

按最大属性值Django对对象进行排序