gpt4 book ai didi

python - 如何将 NumPy 数组的字符串表示形式转换为 NumPy 数组?

转载 作者:太空宇宙 更新时间:2023-11-04 10:15:15 28 4
gpt4 key购买 nike

函数 numpy.array_repr 可用于创建 NumPy 数组的字符串表示形式。如何将 NumPy 数组的字符串表示形式转换为 NumPy 数组?

假设字符串表示如下:

array([-0.00470366,  0.00253503,  0.00306358, -0.00354276,  0.00743946,
-0.00313205, 0.00318478, 0.0074185 , -0.00312317, 0.00127158,
0.00249559, 0.00140165, 0.00053142, -0.00685036, 0.01367841,
-0.0024475 , 0.00120164, -0.00665447, 0.00145064, 0.00128595,
-0.00094848, 0.0028348 , -0.01571732, -0.00150459, 0.00502642,
-0.00259262, 0.00222584, 0.00431143, -0.00379282, 0.00630756,
0.001324 , -0.00420992, -0.00808643, 0.00180546, 0.00586163,
0.00177767, -0.0011724 , -0.00270304, 0.00505948, 0.00627092,
-0.00496326, 0.00460142, -0.00177408, -0.00066973, 0.00226059,
0.00501507, -0.00261056, -0.00617777, 0.00269939, -0.01023268,
0.00338639, 0.00483614, 0.00086805, 0.00041314, -0.0099909 ,
0.00356182, -0.00788026, 0.00245763, 0.00371736, 0.00343493,
-0.00037843, -0.0013632 , -0.00210518, 0.00362144, 0.00061659,
-0.0008905 , -0.01148648, -0.00292173, -0.00206425, 0.00606295,
0.0041656 , -0.00407792, 0.00026893, 0.00078469, 0.00186181,
0.00067565, -0.00811732, 0.00257632, 0.00177333, -0.00602056,
0.00853466, 0.0016037 , 0.00094006, -0.00018953, -0.00408413,
-0.00994886, 0.01268128, 0.0080336 , 0.00546633, 0.00372206,
0.00228082, 0.00445107, 0.00236268, 0.01059031, -0.00106609,
-0.00055983, 0.00371333, 0.0004037 , 0.00632817, 0.00145055], dtype=float32)

如何将其转换为 NumPy 数组?

最佳答案

eval 可能是最简单的。它评估给定的字符串,就好像它是代码一样。

from numpy import array, all
arr_1 = array([1,2,3])
arr_string = repr(arr_1)
arr_2 = eval(arr_string)

all(arr_1 == arr_2) # True

另请参阅有关eval 的文档:https://docs.python.org/2/library/functions.html#eval

关于python - 如何将 NumPy 数组的字符串表示形式转换为 NumPy 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35750639/

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