mvd*_*mvd 8 python numpy scipy
如何从字符串中读取numpy数组?拿一个字符串:
[[ 0.5544 0.4456], [ 0.8811 0.1189]]
Run Code Online (Sandbox Code Playgroud)
并将其转换为数组:
a = from_string("[[ 0.5544 0.4456], [ 0.8811 0.1189]]")
Run Code Online (Sandbox Code Playgroud)
哪里a成为对象:np.array([[0.5544, 0.4456], [0.8811, 0.1189]])
更新:
我正在寻找一个非常简单的界面.一种将2D数组(浮点数)转换为字符串然后再读取它们以重建数组的方法:
arr_to_string(array([[0.5544, 0.4456], [0.8811, 0.1189]])) 应该回来 "[[ 0.5544 0.4456], [ 0.8811 0.1189]]"
string_to_arr("[[ 0.5544 0.4456], [ 0.8811 0.1189]]") 应该返回对象 array([[0.5544, 0.4456], [0.8811, 0.1189]])
理想情况下,如果arr_to_string有一个精度参数来控制转换为字符串的浮点精度,那么你就不会得到像这样的条目0.4444444999999999999999999.
我无法在numpy docs中找到这两种方式.np.save让你创建一个字符串但是没有办法重新加载它(np.load只适用于文件.)
hpa*_*ulj 10
挑战在于不仅要保存数据缓冲区,还要保存形状和dtype. np.fromstring读取数据缓冲区,但作为1d数组; 你必须得到其他地方的dtype和形状.
In [184]: a=np.arange(12).reshape(3,4)
In [185]: np.fromstring(a.tostring(),int)
Out[185]: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
In [186]: np.fromstring(a.tostring(),a.dtype).reshape(a.shape)
Out[186]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
Run Code Online (Sandbox Code Playgroud)
保存Python对象的历史悠久的机制是pickle,并且numpy符合pickle:
In [169]: import pickle
In [170]: a=np.arange(12).reshape(3,4)
In [171]: s=pickle.dumps(a*2)
In [172]: s
Out[172]: "cnumpy.core.multiarray\n_reconstruct\np0\n(cnumpy\nndarray\np1\n(I0\ntp2\nS'b'\np3\ntp4\nRp5\n(I1\n(I3\nI4\ntp6\ncnumpy\ndtype\np7\n(S'i4'\np8\nI0\nI1\ntp9\nRp10\n(I3\nS'<'\np11\nNNNI-1\nI-1\nI0\ntp12\nbI00\nS'\\x00\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x06\\x00\\x00\\x00\\x08\\x00\\x00\\x00\\n\\x00\\x00\\x00\\x0c\\x00\\x00\\x00\\x0e\\x00\\x00\\x00\\x10\\x00\\x00\\x00\\x12\\x00\\x00\\x00\\x14\\x00\\x00\\x00\\x16\\x00\\x00\\x00'\np13\ntp14\nb."
In [173]: pickle.loads(s)
Out[173]:
array([[ 0, 2, 4, 6],
[ 8, 10, 12, 14],
[16, 18, 20, 22]])
Run Code Online (Sandbox Code Playgroud)
有一个numpy函数可以读取pickle字符串:
In [181]: np.loads(s)
Out[181]:
array([[ 0, 2, 4, 6],
[ 8, 10, 12, 14],
[16, 18, 20, 22]])
Run Code Online (Sandbox Code Playgroud)
你提到np.save了一个字符串,但你不能使用np.load.解决这个问题的方法是进一步深入代码,然后使用np.lib.npyio.format.
In [174]: import StringIO
In [175]: S=StringIO.StringIO() # a file like string buffer
In [176]: np.lib.npyio.format.write_array(S,a*3.3)
In [177]: S.seek(0) # rewind the string
In [178]: np.lib.npyio.format.read_array(S)
Out[178]:
array([[ 0. , 3.3, 6.6, 9.9],
[ 13.2, 16.5, 19.8, 23.1],
[ 26.4, 29.7, 33. , 36.3]])
Run Code Online (Sandbox Code Playgroud)
该save字符串有一个标题dtype和shape信息:
In [179]: S.seek(0)
In [180]: S.readlines()
Out[180]:
["\x93NUMPY\x01\x00F\x00{'descr': '<f8', 'fortran_order': False, 'shape': (3, 4), } \n",
'\x00\x00\x00\x00\x00\x00\x00\x00ffffff\n',
'@ffffff\x1a@\xcc\xcc\xcc\xcc\xcc\xcc#@ffffff*@\x00\x00\x00\x00\x00\x800@\xcc\xcc\xcc\xcc\xcc\xcc3@\x99\x99\x99\x99\x99\x197@ffffff:@33333\xb3=@\x00\x00\x00\x00\x00\x80@@fffff&B@']
Run Code Online (Sandbox Code Playgroud)
如果你想要一个人类可读的字符串,你可以试试json.
In [196]: import json
In [197]: js=json.dumps(a.tolist())
In [198]: js
Out[198]: '[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]'
In [199]: np.array(json.loads(js))
Out[199]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
Run Code Online (Sandbox Code Playgroud)
进出数组的列表表示是最明显的用法json.有人可能已经编写了更精细json的数组表示.
你也可以去csv格式化路线 - 有很多关于读/写csv数组的问题.
'[[ 0.5544 0.4456], [ 0.8811 0.1189]]'
Run Code Online (Sandbox Code Playgroud)
为此目的是一个糟糕的字符串表示.它确实看起来很像str()一个数组,但,代替\n.但是没有一种简洁的方法来解析嵌套[],丢失的分隔符很痛苦.如果它一直使用,,那么json可以将其转换为列表.
np.matrix 接受类似MATLAB的字符串:
In [207]: np.matrix(' 0.5544, 0.4456;0.8811, 0.1189')
Out[207]:
matrix([[ 0.5544, 0.4456],
[ 0.8811, 0.1189]])
In [208]: str(np.matrix(' 0.5544, 0.4456;0.8811, 0.1189'))
Out[208]: '[[ 0.5544 0.4456]\n [ 0.8811 0.1189]]'
Run Code Online (Sandbox Code Playgroud)
转发到字符串:
import numpy as np
def array2str(arr, precision=None):
s=np.array_str(arr, precision=precision)
return s.replace('\n', ',')
Run Code Online (Sandbox Code Playgroud)
向后数组:
import re
import ast
import numpy as np
def str2array(s):
# Remove space after [
s=re.sub('\[ +', '[', s.strip())
# Replace commas and spaces
s=re.sub('[,\s]+', ', ', s)
return np.array(ast.literal_eval(s))
Run Code Online (Sandbox Code Playgroud)
如果您使用repr()将数组转换为字符串,则转换将是微不足道的。
如果您的内部列表中的数字之间没有逗号,我不确定是否有一种简单的方法可以做到这一点,但是如果您这样做了,那么您可以使用ast.literal_eval:
import ast
import numpy as np
s = '[[ 0.5544, 0.4456], [ 0.8811, 0.1189]]'
np.array(ast.literal_eval(s))
array([[ 0.5544, 0.4456],
[ 0.8811, 0.1189]])
Run Code Online (Sandbox Code Playgroud)
编辑:我还没有对它进行太多测试,但是您可以使用re在需要它们的地方插入逗号:
import re
s1 = '[[ 0.5544 0.4456], [ 0.8811 -0.1189]]'
# Replace spaces between numbers with commas:
s2 = re.sub('(\d) +(-|\d)', r'\1,\2', s1)
s2
'[[ 0.5544,0.4456], [ 0.8811,-0.1189]]'
Run Code Online (Sandbox Code Playgroud)
然后交给ast.literal_eval:
np.array(ast.literal_eval(s2))
array([[ 0.5544, 0.4456],
[ 0.8811, -0.1189]])
Run Code Online (Sandbox Code Playgroud)
(您需要小心匹配数字之间的空格以及数字和减号之间的空格)。
| 归档时间: |
|
| 查看次数: |
9561 次 |
| 最近记录: |