在python中将数组的字符串表示形式转换为numpy数组

jdm*_*cbr 6 python numpy

我可以列表的字符串表示转换到一个列表ast.literal_eval.是否有一个numpy数组的等价物?

x = arange(4)
xs = str(x)
xs
'[0 1 2 3]'
# how do I convert xs back to an array
Run Code Online (Sandbox Code Playgroud)

使用ast.literal_eval(xs)加注a SyntaxError.如果需要,我可以进行字符串解析,但我认为可能有更好的解决方案.

Mer*_*lin 10

从这开始:

 x = arange(4)
 xs = str(x)
 xs

'[0 1 2 3]'    
Run Code Online (Sandbox Code Playgroud)

试试这个:

import re, ast
xs = re.sub('\s+', ',', xs)
a  = np.array(ast.literal_eval(xs))
a

array([0, 1, 2, 3])    
Run Code Online (Sandbox Code Playgroud)

  • 原因很简单。答案不适用于给出的代码示例! (2认同)

Da *_*ong 5

对于一维数组,Numpy具有一个称为的函数fromstring,因此无需额外的库即可非常有效地完成此操作。

简要地说,您可以像这样解析字符串:

s = '[0 1 2 3]'
a = np.fromstring(s[1:-1], dtype=np.int, sep=' ')
print(a) # [0 1 2 3]
Run Code Online (Sandbox Code Playgroud)

对于nD阵列,可以使用.replace()移除支架并将.reshape()其重塑为所需形状的方法,或者使用Merlin的解决方案。