numpy.array 转字符串

a = numpy.array([[1,2],[3,4]])
s = str(a)
a.savetxt()

字符串 转 numpy.array

此处特指由 numpy.array 转换而得字符串,如上文的snumpy没有给直接转换的函数,需要自己写

import ast
import re
a = np.array([[1,2], [3,4]])
text = str(a)

# 将,替换为空格
text = text.replace(",", " ")

# 去除换行
text = text.replace('\n', '')

# 添加 ','
xs = re.sub('\s+', ',', text)

# 转换回numpy.array
a = np.array(ast.literal_eval(xs))
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐