python numpy 中ndarry转成string后怎么转回来
问题描述:
我用request.post()发送请求,data中数组不会传,所以想把数组转成string,得知
ndarray可以通过方式tostring将ndarry形式的数据转成string ,但不知道怎么转回来。,
求大神指教
答
没有发现修改的地方,推荐使用第二种方式,pickle模块在python3内置,不需要传递额外的参数
答
re.split()是一种方法
答
import json
data = 你要POST的数据
respone = requests.post(url,datas = json.dumps(data))
答
转载自:Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray
使用tostring()方法得到的字符串会丢失原始数据中的的类型(type)信息和维度(shape)信息,这意味着你要将这两个信息一起传送给接收者
>>> import numpy as np
>>> a = np.arange(12).reshape(3, 4)
>>> a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> s = a.tostring()
>>> aa = np.fromstring(a)
>>> aa
array([ 0.00000000e+000, 4.94065646e-324, 9.88131292e-324,
1.48219694e-323, 1.97626258e-323, 2.47032823e-323,
2.96439388e-323, 3.45845952e-323, 3.95252517e-323,
4.44659081e-323, 4.94065646e-323, 5.43472210e-323])
>>> aa = np.fromstring(a, dtype=int)
>>> aa
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
>>> aa = np.fromstring(a, dtype=int).reshape(3, 4)
>>> aa
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
为了自动保持对象的一致性,可以使用cPickle,如果你是使用python3的话,可以直接使用pickle
>>> import cPickle
>>> s = cPickle.dumps(a)
>>> cPickle.loads(s)
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])