将numpy.ndarray转换为字符串(或字节),然后将其转换回numpy.ndarray [英] Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray

查看:3671
本文介绍了将numpy.ndarray转换为字符串(或字节),然后将其转换回numpy.ndarray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里遇到麻烦

我正在尝试将numpy.ndarray转换为字符串,我已经这样做了:

I'm trying to convert a numpy.ndarray to string, I've already done that like this:

randomArray.tostring()

它可以工作,但是我想知道是否可以将其转换回numpy.ndarray.

It works, but I'm wondering if I can transform it back to a numpy.ndarray.

做到这一点的最佳方法是什么?

What's the best way to do this?

我正在使用numpy 1.8.1

I'm using numpy 1.8.1

上下文: 目的是将numpy.ndarray作为消息发送到Rabbitmq(pika库)

Context: The objective is to send the numpy.ndarray as a message in rabbitmq (pika library)

推荐答案

您可以为此使用fromstring()方法:

You can use the fromstring() method for this:

arr =np.array([1,2,3,4,5,6])
ts = arr.tostring()
print np.fromstring(ts,dtype=int)

>>>[1 2 3 4 5 6]

对不起,我的回答很简短,没有足够的意见发表意见.请记住声明数据类型,否则您将陷入痛苦的境地.

Sorry for the short answer, not enough points for commenting. Remember to state the data types or you'll end up in a world of pain.

从numpy 1.14开始的"fromstring"注释:

sep:str,可选

sep : str, optional

用字符串分隔数据中的数字;元素之间的多余空格也将被忽略.

The string separating numbers in the data; extra whitespace between elements is also ignored.

从版本1.14开始不建议使用:默认情况下,不建议传递sep ='',因为它将触发此功能的不建议使用的二进制模式.此模式将字符串解释为二进制字节,而不是使用带十进制数字的ASCII文本,此操作最好从buffer(string,dtype,count)进行拼写.如果string包含unicode文本,则fromstring的二进制模式将首先使用utf-8(python 3)或默认编码(python 2)将其编码为字节,而这两种方法均不会产生合理的结果.

Deprecated since version 1.14: Passing sep='', the default, is deprecated since it will trigger the deprecated binary mode of this function. This mode interprets string as binary bytes, rather than ASCII text with decimal numbers, an operation which is better spelt frombuffer(string, dtype, count). If string contains unicode text, the binary mode of fromstring will first encode it into bytes using either utf-8 (python 3) or the default encoding (python 2), neither of which produce sane results.

这篇关于将numpy.ndarray转换为字符串(或字节),然后将其转换回numpy.ndarray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆