从字典写入 numpy 数组

2023-12-02

我有一个文件头值(时间、帧数、年、月等)的字典,我想将其写入 numpy 数组。我目前的代码如下:

    arr=np.array([(k,)+v for k,v in fileheader.iteritems()],dtype=["a3,a,i4,i4,i4,i4,f8,i4,i4,i4,i4,i4,i4,a10,a26,a33,a235,i4,i4,i4,i4,i4,i4"])

但我收到一个错误,“只能将元组(而不是“int”)连接到元组。

基本上,最终结果需要是存储整个文件头信息(512 字节)和每个帧的数据(头和数据,每帧 49408 字节)的数组。有没有更简单的方法来做到这一点?

编辑:为了澄清(也为我自己),我需要将文件每一帧的数据写入数组。我得到了 matlab 代码作为基础。这是给我的代码的粗略想法:

data.frame=zeros([512 96])
frame=uint8(fread(fid,[data.numbeams,512]),'uint8'))
data.frame=frame

如何将“框架”翻译成Python?


您最好将标题数据保留在 dict 中。你真的需要它作为一个数组吗? (如果是这样,为什么?将标头放在 numpy 数组中有一些优点,但它比简单的dict,并且不那么灵活。)

一个缺点是dict是它的键没有可预测的顺序。如果您需要以常规顺序(类似于 C 结构体)将标头写回到磁盘,那么您需要单独存储字段的顺序及其值。如果是这种情况,您可能会考虑使用有序字典(collections.OrderedDict)或者只是组合一个简单的类来保存标头数据并在那里存储顺序。

除非有充分的理由将其放入 numpy 数组中,否则您可能不想这样做。

然而,结构化数组将保留标头的顺序,并使将其二进制表示形式写入磁盘变得更容易,但它在其他方面不灵活。

如果你确实想让标头成为一个数组,你可以这样做:

import numpy as np

# Lists can be modified, but preserve order. That's important in this case.
names = ['Name1', 'Name2', 'Name3']
# It's "S3" instead of "a3" for a string field in numpy, by the way
formats = ['S3', 'i4', 'f8'] 

# It's often cleaner to specify the dtype this way instead of as a giant string
dtype = dict(names=names, formats=formats)

# This won't preserve the order we're specifying things in!!
# If we iterate through it, things may be in any order.
header = dict(Name1='abc', Name2=456, Name3=3.45)

# Therefore, we'll be sure to pass things in in order...
# Also, np.array will expect a tuple instead of a list for a structured array...
values = tuple(header[name] for name in names)
header_array = np.array(values, dtype=dtype)

# We can access field in the array like this...
print header_array['Name2']

# And dump it to disk (similar to a C struct) with
header_array.tofile('test.dat')

另一方面,如果您只想访问标头中的值,只需将其保留为dict。这样就更简单了。


根据听起来你在做什么,我会做这样的事情。我使用 numpy 数组读取标头,但标头值实际上存储为类属性(以及标头数组)。

这看起来比实际情况更复杂。

我只是定义两个新类,一个用于父文件,一个用于框架。您可以使用更少的代码来完成同样的事情,但这为您提供了更复杂的事情的基础。

import numpy as np

class SonarFile(object):
    # These define the format of the file header
    header_fields = ('num_frames', 'name1', 'name2', 'name3')
    header_formats = ('i4', 'f4', 'S10', '>I4')

    def __init__(self, filename):
        self.infile = open(filename, 'r')
        dtype = dict(names=self.header_fields, formats=self.header_formats)

        # Read in the header as a numpy array (count=1 is important here!)
        self.header = np.fromfile(self.infile, dtype=dtype, count=1)

        # Store the position so we can "rewind" to the end of the header
        self.header_length = self.infile.tell()

        # You may or may not want to do this (If the field names can have
        # spaces, it's a bad idea). It will allow you to access things with
        # sonar_file.Name1 instead of sonar_file.header['Name1'], though.
        for field in self.header_fields:
            setattr(self, field, self.header[field])

    # __iter__ is a special function that defines what should happen when we  
    # try to iterate through an instance of this class.
    def __iter__(self):
        """Iterate through each frame in the dataset."""
        # Rewind to the end of the file header
        self.infile.seek(self.header_length)

        # Iterate through frames...
        for _ in range(self.num_frames):
            yield Frame(self.infile)

    def close(self):
        self.infile.close()

class Frame(object):
    header_fields = ('width', 'height', 'name')
    header_formats = ('i4', 'i4', 'S20')
    data_format = 'f4'

    def __init__(self, infile):
        dtype = dict(names=self.header_fields, formats=self.header_formats)
        self.header = np.fromfile(infile, dtype=dtype, count=1)

        # See discussion above...
        for field in self.header_fields:
            setattr(self, field, self.header[field])

        # I'm assuming that the size of the frame is in the frame header...
        ncols, nrows = self.width, self.height

        # Read the data in
        self.data = np.fromfile(infile, self.data_format, count=ncols * nrows)

        # And reshape it into a 2d array.
        # I'm assuming C-order, instead of Fortran order.
        # If it's fortran order, just do "data.reshape((ncols, nrows)).T"
        self.data = self.data.reshape((nrows, ncols))

你会像这样使用它:

dataset = SonarFile('input.dat')

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

从字典写入 numpy 数组 的相关文章

随机推荐

  • 如何在 Java 中使用“Startswith”变量查找文件

    我试图根据每次迭代从 Excel 工作表中提取的前 8 个数字找到一个文件 每当我使用下面的代码时 我都会收到错误消息 封闭范围中定义的局部变量 CaseID 必须是最终的或有效的最终 我还是个新手 所以我不确定如何解决这个问题 尽管这听起
  • 在 Jade include 中使用变量

    我正在使用 Jade 和 Express 我想在我的 include 语句中使用一个变量 例如 app js app get admin function req res var Admin require routes admin app
  • 派生类的虚拟赋值运算符未被调用

    我对 C 还很陌生 正在尝试掌握虚拟赋值 下面的程序由一个具有两个数据成员的抽象基类和一个具有一个数据成员的派生类组成 当我设置指向派生对象的抽象指针时 程序使用运算符 的抽象版本而不是派生版本 即使它们都被声明为 虚拟 我在这里做错了什么
  • 如何让我的汉堡动画反转?

    我无法让我的动画顺利运行 我创建了一个汉堡图标 包含三个 div 如下所示 div class container div class burger contain div class line div div class line div
  • 如何在 AutoCompleteTextView 中创建干净的按钮

    如何在 AutoCompleteTextView 中创建干净的按钮 当我单击清除按钮时 我想清除 AutoCompleteTextView 中的所有文本 如图所示 正如中所解释的这个帖子作者 Michael Derazon 您可以扩展 Au
  • 使用 jQuery 同步滚动?

    我正在尝试实现两个同步滚动DIV使用以下代码 DEMO document ready function div1 scroll function div2 scrollTop div1 scrollTop div2 scroll funct
  • 绝对与相对位置宽度和高度

    我知道什么是绝对位置和相对位置 但有些点我仍然不清楚 以供参考 css rel position relative background red abs position absolute background blue html div
  • 将列表拆分为较小的相等值列表

    我希望将一个列表转换为较小的等值列表 我有一个例子是 a a a b b c c c c to a a a b b c c c c 您认为做到这一点最有效的方法是什么 你可以使用itertools groupby解决问题 gt gt gt
  • 使用 SQL 查找缺失的日期

    我在表中有一些超过两年的日期作为示例日期 01 jan 2012 02 jan 2012 04 jan 2012 05 jan 2012 06 jan 2012 07 jan 2012 09 jan 2012 11 jan 2012 01
  • JavaScript 中如何检查字符串数组是否包含一个字符串? [复制]

    这个问题在这里已经有答案了 我有一个字符串数组和一个字符串 我想根据数组值测试这个字符串 并对结果应用一个条件 如果数组包含字符串 则执行 A 否则执行 B 我怎样才能做到这一点 有一个indexOf所有数组 Internet Explor
  • Git 命令可以在终端中运行,但不能在 groovy 脚本中运行

    以下 git 命令适用于 Android Studio 终端 git no pager show s format an
  • 有什么方法可以使递归函数更快吗?

    经过对递归函数的一些研究后 我面临着矛盾 一方面以递归方式解决问题很优雅 但另一方面在实践中性能似乎很糟糕并且递归调用的数量是有限的 我知道默认情况下 Python 的递归深度限制为 1000 但是即使在一个简单的应用程序中 早在 40 5
  • 在一个进程多个数据库连接 sinatra 应用程序中使用什么 ORM?

    检查了 ActiveRecord DataMapper Sequel 有些使用全局变量 静态变量 有些需要在加载模型源文件之前打开数据库连接 在使用不同数据库的 sinatra 应用程序中使用什么 ORM 更好 DataMapper 专为多
  • 从 Invoke-Command 执行嵌套 ScriptBlock 时出现错误

    我正在寻找创建包装器的方法Invoke Command在调用我的命令之前 它会恢复我在远程计算机上使用的当前目录 这是我尝试做的 function nice invoke param string Computer scriptblock
  • 在路径 DexPathList 上找不到类

    我试图将我的项目更新到 targetSdk 23 但考虑到所有的弃用 我决定不准备这样做 我不想经历它 所以我在 Mercurial 上恢复到旧版本 现在我得到的只是这个错误 而且我无法让该死的应用程序再次运行 可能出了什么问题 12 21
  • 使用 DryIoc 解决多个注册之一

    鉴于下面的小例子 有没有一种方法可以标记 属性 名称约定 MyInterface论证中MyService2 这样它将正确解析 或者是传入的唯一方法MyInterface 我知道Castle Windsor可以根据命名约定来解析它 但我在Dr
  • Shiny:是否有办法仅在单击 Shiny 地图后才启用鼠标滚轮缩放?

    有没有办法仅在第一次单击地图后启用鼠标滚轮缩放 我有以下代码 其中我只想在单击地图后缩放地图 有没有办法在闪亮的情况下做到这一点 library shiny library leaflet library maps ui lt fluidP
  • html 页面中的文本突出显示

    我正在使用 jquery 处理 HTML 我想制作一个网页来一次突出显示该页面中的一些文本行 第 15 22 32 行 这可以通过单击鼠标左键并拖动该行来完成 以便选择具有蓝色背景的文本行 我可以使用 jquery 获取选定的行 如下所示
  • 使用估算数据集时 svydesign 出现错误

    我正在使用 svydesign 分析估算数据集 但出现错误 下面是代码 library mitools library survey data nhanes nhanes hyp lt as factor nhanes hyp imp lt
  • 从字典写入 numpy 数组

    我有一个文件头值 时间 帧数 年 月等 的字典 我想将其写入 numpy 数组 我目前的代码如下 arr np array k v for k v in fileheader iteritems dtype a3 a i4 i4 i4 i4