【问题标题】:Two implementations of Numpy fromfile?Numpy fromfile 的两种实现?
【发布时间】:2017-08-12 04:12:41
【问题描述】:

我正在尝试更新一些在方法中使用np.fromfile 的遗留代码。当我尝试搜索该方法的 numpy 源时,我只找到 np.core.records.fromfile,但是当您搜索文档时,您可以找到 np.fromfile。看看这两种方法,你会发现它们有不同的 kwargs,这让我觉得它们完全是不同的方法。

我的问题是:

1) np.fromfile 的来源在哪里?

2) 为什么同一个名字下有两个不同的函数?如果您不注意两者的行为差异,这显然会让人感到困惑。具体来说,np.core.records.fromfile 将引发错误,如果您尝试读取的字节数超过文件包含的字节数,而 np.fromfile 则不会。您可以在下面找到一个最小的示例。

In [1]: import numpy as np

In [2]: my_bytes = b'\x04\x00\x00\x00\xac\x92\x01\x00\xb2\x91\x01'

In [3]: with open('test_file.itf', 'wb') as f:
            f.write(my_bytes)

In [4]: with open('test_file.itf', 'rb') as f:
            result = np.fromfile(f, 'int32', 5)

In [5]: result
Out [5]: 

In [6]: with open('test_file.itf', 'rb') as f:
            result = np.core.records.fromfile(f, 'int32', 5)
ValueError: Not enough bytes left in file for specified shape and type

【问题讨论】:

  • 是的,您正在链接到np.core.records.fromfile 的源代码,它专门用于处理记录数组。
  • @juanpa.arrivillaga 我知道这一点。不幸的是,这是我可以在源代码中找到的唯一实现的 fromfile 声明。我想知道在哪里可以找到np.fromfile的来源
  • records版本的本质是创建一个dtype和shape正确的接收者数组,并使用二进制文件readinto方法将字节加载到它的.data属性中。
  • core.records 的东西是numpy 的死水。 structured arrays,没有records覆盖更常见,通常由genfromtxtcsv文件生成。

标签: python python-3.x numpy binary fromfile


【解决方案1】:

如果你在np.fromfile 上使用help,你会发现一些非常...有用的东西:

Help on built-in function fromfile in module numpy.core.multiarray:

fromfile(...)
    fromfile(file, dtype=float, count=-1, sep='')

    Construct an array from data in a text or binary file.

    A highly efficient way of reading binary data with a known data-type,
    as well as parsing simply formatted text files.  Data written using the
    `tofile` method can be read using this function.

据我所知,这是用 C 语言实现的,可以在 here 找到。

如果您尝试保存和加载二进制数据,则不应再使用np.fromfile。您应该使用np.savenp.load,它们将使用与平台无关的二进制格式。

【讨论】:

  • 要了解C 链接,您需要进一步挖掘并找到PyArray_FromFile 的实现。 numpy 内置函数对凡人来说是个谜。
  • @hpaulj 嘿,是的,这对于 numpy 来说非常典型。用 C 编写的 array_some_function 本质上是用 C 编写的 PyArray_SomeFunction 的包装器......祝你好运追踪 PyArray_SomeFunction
猜你喜欢
  • 2019-07-28
  • 1970-01-01
  • 2018-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多