gpt4 book ai didi

python - Numpy 从字符串解析为 ndarray

转载 作者:行者123 更新时间:2023-12-04 01:32:03 27 4
gpt4 key购买 nike

我已将服务器端传递给客户端的 ndarray 字符串化,该数组的示例如下所示

import numpy as np

str_array = "[[0.1233 0.333 4.1111] [0.1233 0.333 4.1111] [0.1233 0.333 4.1111]]"
arr = np.fromstring(str_array, dtype=np.float32, sep = ' ')

print(arr)

当我运行该代码时,它会引发一条错误消息:

  File "example.py", line 89, in <module>
arr = np.fromstring(str_array, dtype=np.float32)
ValueError: string size must be a multiple of element size

我希望我的字符串化数组再次成为 ndarray。我该如何解决这个问题?

最佳答案

使用numpy.matrix而不是 reshape

>>> np.matrix(str_array).reshape(-1,3)
matrix([[0.1233, 0.333 , 4.1111],
[0.1233, 0.333 , 4.1111],
[0.1233, 0.333 , 4.1111]])

或者获取 ndarray 使用属性 matrix.A

>>> np.matrix(str_array).reshape(-1,3).A
array([[0.1233, 0.333 , 4.1111],
[0.1233, 0.333 , 4.1111],
[0.1233, 0.333 , 4.1111]])

关于python - Numpy 从字符串解析为 ndarray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60752440/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com