numpy:gzip 压缩文件的 fromfile

2024-04-27

我在用numpy.fromfile构造一个数组,我可以将其传递给pandas.DataFrame构造函数

import numpy as np
import pandas as pd

def read_best_file(file, **kwargs):
    '''
    Loads best price data into a dataframe
    '''
    names   = [ 'time', 'bid_size', 'bid_price', 'ask_size', 'ask_price' ]
    formats = [ 'u8',   'i4',       'f8',        'i4',       'f8'        ]
    offsets = [  0,      8,          12,          20,         24         ]

    dt = np.dtype({
            'names': names, 
            'formats': formats,
            'offsets': offsets 
        })
    return pd.DataFrame(np.fromfile(file, dt))

我想扩展此方法以处理 gzip 压缩文件。

根据numpy.fromfile http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromfile.html文档,第一个参数是文件:

file : file or str
Open file object or filename

因此,我添加了以下内容来检查 gzip 文件路径:

if isinstance(file, str) and file.endswith(".gz"):
    file = gzip.open(file, "r")

但是,当我尝试将其传递给fromfile构造函数我得到一个IOError:

IOError: first argument must be an open file

问题:

我怎样才能打电话numpy.fromfile使用 gzip 压缩文件?

Edit:

根据评论中的请求,显示检查 gzip 压缩文件的实现:

def read_best_file(file, **kwargs):
    '''
    Loads best price data into a dataframe
    '''
    names   = [ 'time', 'bid_size', 'bid_price', 'ask_size', 'ask_price' ]
    formats = [ 'u8',   'i4',       'f8',        'i4',       'f8'        ]
    offsets = [  0,      8,          12,          20,         24         ]

    dt = np.dtype({
            'names': names, 
            'formats': formats,
            'offsets': offsets 
        })

    if isinstance(file, str) and file.endswith(".gz"):
        file = gzip.open(file, "r")

    return pd.DataFrame(np.fromfile(file, dt))

我通过 numpy.frombuffer() 提供 read() 结果,成功地从 gzipped 文件中读取原始二进制数据数组。此代码适用于 Python 3.7.3,也许也适用于早期版本。

# Example: read short integers (signed) from gzipped raw binary file

import gzip
import numpy as np

fname_gzipped = 'my_binary_data.dat.gz'
raw_dtype = np.int16
with gzip.open(fname_gzipped, 'rb') as f:
    from_gzipped = np.frombuffer(f.read(), dtype=raw_dtype)

# Demonstrate equivalence with direct np.fromfile()
fname_raw = 'my_binary_data.dat'
from_raw = np.fromfile(fname_raw, dtype=raw_dtype)

# True
print('raw binary and gunzipped are the same: {}'.format(
    np.array_equiv(from_gzipped, from_raw)))

# False
wrong_dtype = np.uint8
binary_as_wrong_dtype = np.fromfile(fname_raw, dtype=wrong_dtype)
print('wrong dtype and gunzipped are the same: {}'.format(
    np.array_equiv(from_gzipped, binary_as_wrong_dtype)))

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

numpy:gzip 压缩文件的 fromfile 的相关文章

  • ipdb 和 pdb++ 之间的区别?

    Python 有一个名为 pdb 的默认调试器 但社区创建了一些替代品 其中两个是ipdb https github com gotcha ipdb and pdb https github com pdbpp pdbpp 它们似乎迎合了相
  • Celery计划任务中的打印语句不会出现在终端中

    当我跑步时celery A tasks2 celery worker B我想看到每秒打印 芹菜任务 目前没有打印任何内容 为什么这不起作用 from app import app from celery import Celery from
  • 带有指针数组的 cython

    我在 python 中有一个 numpy ndarrays 列表 具有不同的长度 并且需要非常快速地访问 python 中的列表 我认为指针数组就可以解决问题 我试过 float type t list of arrays no of ar
  • 帮助需要在可选条件下编写正则表达式[关闭]

    我有一个日志文件包含如下内容 log Using data from yyyy mm dd 2011 8 3 0 files queued for scanning Warning E test H ndler pdf File not F
  • 创建圆形图像 PIL Tkinter

    Currently I have a zoom feature in my application that works very well however I d like the actual zoom box to be a circ
  • 引发 RuntimeError(f"目录 '{directory}' 不存在") RuntimeError: 导入 fitz 时目录 'static/' 不存在

    当我运行 extract img py 文件时出现此错误 RuntimeError f 目录 directory 不存在 运行时错误 导入 fitz 时不存在目录 static 我不明白为什么这会给我发回此错误消息 我之前看到过关于这个话题
  • Django 如何从 ManyToManyField 序列化并列出全部

    我正在使用 Django 1 9 1 开发移动应用程序后端 我实现了关注者模型 现在我想列出用户的所有关注者 但目前我不得不这样做 我还使用 Django Rest 框架 这是我的 UserProfile 模型 class UserProf
  • Python 使用 M2Crypto 通过 S/MIME 对消息进行签名

    我现在花了几个小时 但找不到我的错误 我想要一个简单的例程来创建 S MIME 签名消息 稍后可以与 smtplib 一起使用 这是我到目前为止所拥有的 usr bin python2 7 coding utf 8 from future
  • 十六进制数的按位异或

    我们如何在 Python 中对十六进制数进行异或 例如 我想要异或 ABCD and 12EF 答案应该是 B922 我使用了下面的代码 但它给出了错误的结果 xor two strings of different lengths def
  • Selenium Webdriver - Python - leboncoin - pb 选择带重音的按钮

    我正在尝试在以下网站上自动填写表格 https www leboncoin fr https www leboncoin fr 我用 Selenium IDE 录制了一个脚本 我有一个通过单击 Se 连接器 按钮并填写我的密码和用户名来自动
  • Pyinstaller --onefile 警告文件已存在但不应存在

    跑步时Pyinstaller onefile 并开始得到结果 exe 会出现多个弹出窗口 并显示以下警告 WARNING file already exists but should not C Users myuser AppData L
  • 在ansible中合并字典

    我目前正在构建一个使用 ansible 安装 PHP 的角色 并且在合并字典时遇到一些困难 我尝试了多种方法来做到这一点 但我无法让它像我想要的那样工作 A vars file my default values key value my
  • 如何使用python读取最后一行的特定位置

    我有一个太大的 txt 文件 并且有几行类似的行 如下所示 字1 字2 字3 字4 553 75 我对位置 4 值 感兴趣 即最后一行 553 75 我的文件文本 word1 word2 word3 word4 553 20 word1 w
  • 如何使用 jira-python 设置 fixVersions 字段

    我正在尝试使用 jira python 模块 http jira python readthedocs org en latest 更新现有的 JIRA 具体来说 我正在尝试设置问题的fixesVersion 列表 我已经尝试了一段时间但没
  • 管理文件字段当前 url 不正确

    在 Django 管理中 只要有 FileField 编辑页面上就会有一个 当前 框 其中包含指向当前文件的超链接 但是 此链接会附加到当前页面 url 因此会导致 404 因为不存在这样的页面 例如 http 127 0 0 1 8000
  • 如何在 Python 中仅列出 zip 存档中的文件夹?

    如何仅列出 zip 存档中的文件夹 这将列出存档中的每个文件夹和文件 import zipfile file zipfile ZipFile samples sample zip r for name in file namelist pr
  • psutil:测量特定进程的CPU使用率

    我正在尝试测量进程树的 cpu 使用率 目前获取进程 没有子进程 的 cpu usage 就可以了 但我得到了奇怪的结果 import psutil p psutil Process PID p cpu percent 还给我float g
  • 使 matplotlib 图形默认看起来像 R?

    Is there a way to make matplotlib behave identically to R or almost like R in terms of plotting defaults For example R t
  • 在读/写二进制数据结构时访问位域

    我正在为二进制格式编写一个解析器 这种二进制格式涉及不同的表 这些表同样采用二进制格式 通常包含不同的字段大小 其中 50 100 个之间 大多数这些结构都有位域 并且在 C 语言中表示时看起来像这样 struct myHeader uns
  • python中匹配3个或更多相同的字符

    我正在尝试使用正则表达式在字符串中查找三个或更多相同的字符 例如 你好 不匹配 噢 会的 我尝试过做类似的事情 re compile 1 3 a zA Z re compile w 1 5 但似乎都不起作用 w 1 2 是您正在寻找的正则表

随机推荐