简体   繁体   English

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

[英]convert string representation of array to numpy array in python

I can convert a string representation of a list to a list with ast.literal_eval .我可以使用ast.literal_eval 将列表的字符串表示形式转换为列表 Is there an equivalent for a numpy array? numpy 数组是否有等效项?

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

Using ast.literal_eval(xs) raises a SyntaxError .使用ast.literal_eval(xs)引发SyntaxError I can do the string parsing if I need to, but I thought there might be a better solution.如果需要,我可以进行字符串解析,但我认为可能有更好的解决方案。

For 1D arrays, Numpy has a function called fromstring , so it can be done very efficiently without extra libraries.对于一维数组, Numpy 有一个名为fromstring的函数,因此无需额外库即可非常高效地完成。

Briefly you can parse your string like this:简而言之,您可以像这样解析您的字符串:

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

For nD arrays, one can use .replace() to remove the brackets and .reshape() to reshape to desired shape, or use Merlin's solution.对于 nD 数组,可以使用.replace()删除括号并使用.reshape()将其重塑为所需的形状,或者使用 Merlin 的解决方案。

Try this:试试这个:

xs = '[0 1 2 3]'

import re, ast
ls = re.sub('\s+', ',', xs)
a = np.array(ast.literal_eval(ls))
a  # -> array([0, 1, 2, 3])    

if elements of lists are 2D float.如果列表的元素是 2D 浮点数。 ast.literal_eval() cannot handle a lot very complex list of list of nested list. ast.literal_eval() 无法处理很多非常复杂的嵌套列表列表。

Therefore, it is better to parse list of list as dict and dump the string.因此,最好将列表列表解析为 dict 并转储字符串。

while loading a saved dump, ast.literal_eval() handles dict as strings in a better way.在加载保存的转储时, ast.literal_eval() 以更好的方式将 dict 作为字符串处理。 convert the string to dict and then dict to list of list将字符串转换为 dict,然后将 dict 转换为列表列表

k = np.array([[[0.09898942, 0.22804536],[0.06109612, 0.19022354],[0.93369348, 0.53521671],[0.64630094, 0.28553219]],[[0.94503154, 0.82639528],[0.07503319, 0.80149062],[0.1234832 , 0.44657691],[0.7781163 , 0.63538195]]])

d = dict(enumerate(k.flatten(), 1))
d = str(d) ## dump as string  (pickle and other packages parse the dump as bytes)

m = ast.literal_eval(d) ### convert the dict as str to  dict

m = np.fromiter(m.values(), dtype=float) ## convert m to nparray

Use np.matrix to convert a string to a numpy matrix.使用np.matrix将字符串转换为 numpy 矩阵。 Then, use np.asarray to convert the matrix to a numpy array with the same shape.然后,使用np.asarray将矩阵转换为具有相同形状的 numpy 数组。

>>> s = "[1,2]; [3,4]"
>>> a = np.asarray(np.matrix(s)) 
>>> a
array([[1, 2],
       [3, 4]])

In contrast to the accepted answer, this works also for two dimensional arrays.与公认的答案相反,这也适用于二维 arrays。

Another way would be: 另一种方法是:

>>> s = "[1 2 3 4]"
>>> np.array(eval(s.replace(' ',',')))
array([1, 2, 3, 4])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM