Numpy中的frombuffer,S1和S2的区别,前面的|的作用,二进制字符串

Numpy官网上的解释

numpy.frombuffer

numpy.frombuffer(bufferdtype=floatcount=-1offset=0)

Interpret a buffer as a 1-dimensional array.

Parameters:

buffer : buffer_like

An object that exposes the buffer interface.

dtype : data-type, optional

Data-type of the returned array; default: float.

count : int, optional

Number of items to read. -1 means all data in the buffer.

offset : int, optional

Start reading the buffer from this offset (in bytes); default: 0.

Notes

If the buffer has data that is not in machine byte-order, this should be specified as part of the data-type, e.g.:

>>>

>>> dt = np.dtype(int)
>>> dt = dt.newbyteorder('>')
>>> np.frombuffer(buf, dtype=dt)

The data of the resulting array will not be byteswapped, but will be interpreted correctly.

Examples

>>>

>>> s = 'hello world'
>>> np.frombuffer(s, dtype='S1', count=5, offset=6)
array(['w', 'o', 'r', 'l', 'd'],
      dtype='|S1')

>>>

>>> np.frombuffer(b'\x01\x02', dtype=np.uint8)
array([1, 2], dtype=uint8)
>>> np.frombuffer(b'\x01\x02\x03\x04\x05', dtype=np.uint8, count=3)
array([1, 2, 3], dtype=uint8)

Numpy.frombuffer的作用探究

可以实现从已有的数组中创建np.array对象

四个参数作用如下

buffer 流对象

dtype 返回的生成数组的数据类型(可选)

count 读取数据的量(可选)

offset 读取的初始位置

这里的流对象是二进制的

因此若想从string类型中转入,得先转化为bytestring

Example1

import numpy as np

s = b'hello world'
np.frombuffer(s, dtype='S1', count=5, offset=6)

这里的hello world前的b表示这是bytestring

S1表示单个字符串是1个字符

他的输出是

array([b'w', b'o', b'r', b'l', b'd'], dtype='|S1')

也可以用|S1,这里的|会将其转化为bytestring

import numpy as np

s = 'hello world'
np.frombuffer(s, dtype='|S1', count=5, offset=6)

 

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值