NumPy - frombuffer 和 fromstring 有什么区别?

2024-03-03

他们似乎给了我同样的结果:

In [32]: s
Out[32]: '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x15\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

In [27]: np.frombuffer(s, dtype="int8")
Out[27]:
array([ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
    0,  0,  0, 21,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0], dtype=int8)

In [28]: np.fromstring(s, dtype="int8")
Out[28]:
array([ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
    0,  0,  0, 21,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0], dtype=int8)

In [33]: b = buffer(s)

In [34]: b
Out[34]: <read-only buffer for 0x035F8020, size -1, offset 0 at 0x036F13A0>

In [35]: np.fromstring(b, dtype="int8")
Out[35]:
array([ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
    0,  0,  0, 21,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0], dtype=int8)

In [36]: np.frombuffer(b, dtype="int8")
Out[36]:
array([ 0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
    0,  0,  0, 21,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0], dtype=int8)

什么时候应该使用其中一种?


从实际角度来看,区别在于:

x = np.fromstring(s, dtype='int8')

将在内存中复制该字符串,同时:

x = np.frombuffer(s, dtype='int8')

or

x = np.frombuffer(buffer(s), dtype='int8')

将直接使用字符串的内存缓冲区,不会使用任何*额外的内存。使用frombuffer如果输入到buffer是一个字符串,因为字符串在 python 中是不可变的。

(*忽略用于额外 python 的几个字节的内存ndarray对象——数据的底层内存将被共享。)


如果你不熟悉buffer对象(memoryview在 python3.x 中) http://docs.python.org/2/c-api/buffer.html,它们本质上是 C 级库公开内存块以供 python 使用的一种方式。它基本上是一个用于管理原始内存访问的Python 接口。

如果您正在使用暴露缓冲区接口的东西,那么您可能想要使用frombuffer。 (Python 2.x 字符串和 python 3.xbytes公开缓冲区接口,但您将得到一个只读数组,因为 python 字符串是不可变的。)

否则,使用fromstring从字符串创建 numpy 数组。 (除非您知道自己在做什么,并且想要严格控制内存使用等)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

NumPy - frombuffer 和 fromstring 有什么区别? 的相关文章

随机推荐