【问题标题】:Writing to numpy array from dictionary从字典写入numpy数组
【发布时间】:2012-06-06 00:40:16
【问题描述】:

我有一个文件头值字典(时间、帧数、年、月等),我想将其写入 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?

【问题讨论】:

  • 你的错误与numpy无关。它来自[(k,)+v for k,v in fileheader.iteritems()] 中的(k,)+v。听起来您想使用键的名称作为 numpy 数组中的记录名称?如果是这样,您需要构建 dtype 以使用这些名称。另请记住,dicts 是无序的,这可能会导致您现在编写内容的方式出现问题。
  • 谢谢!如何将所有值以有序格式排列? (我基本上没有python经验)

标签: python arrays dictionary numpy


【解决方案1】:

您最好将标题数据保存在 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...

【讨论】:

  • 好吧,我想标题信息不需要在数组中。但是,我确实需要数组中的帧信息来创建图像。在这里忍耐一下——我被扔进了深渊,我的任务是翻译 matlab 代码以进行数据的图像处理。我知道以下内容:文件头是 512 字节,每帧大小为 49408 字节,其中 256 个是帧头,编写 matlab 代码的人设置了一个初始数组,其尺寸为 [512,96] (这是一个有 96 个光束的声纳)。我需要处理每个文件的每一帧。
  • 否定,我想最终将最终数据导出到 .txt 文件中。现在,我需要读入每个文件和相关的图像数据;它是二进制格式。我们的最终结果(沿着这条线)是获取这些图像文件(用声纳相机收集)并在声纳光束中自主定位目标(为了可视化,它本质上是黑色背景上的白色圆圈)。如果有任何意义,我最终需要将检测到的目标的坐标位置存储在文件中。非常感谢您的帮助,我完全是初学者!
  • 哦,顺便说一句——该程序已经在matlab中成功编写(半),我们正在尝试转换为python。
  • 查看更新。希望它有点帮助!有不止一种方法可以做到这一点,你可以用少得多的代码来做我展示的事情,但如果你将来需要更新它,它的灵活性就会降低。我通常发现它最容易按照这些方式做一些事情来读取类似的数据。以相同的格式向磁盘添加写入也非常简单。 (不管有什么价值,我也是一名海洋地球物理学家,而且我最终阅读随机二进制数据格式的次数似乎比我想要的要多得多。)
  • 这个很完美,我试试看!再次感谢您!
【解决方案2】:

问题似乎在于v 是int 而不是tuple。试试:

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"])

【讨论】:

  • k 在这里将是一个字符串,考虑到数组的 dtype,这没有任何意义。 OP 可能只想要v,但我不确定....
  • 我从文件头中的那个变量中获得了每个 dtype...a3 是 3 字符串文件类型,a 是版本,i4 是 int32 帧数,依此类推。文件中的一些标题对应于字符串,一些是浮点数,大多数是 32 位整数。这有帮助吗?
猜你喜欢
  • 2018-03-23
  • 2013-11-28
  • 2018-12-25
  • 2014-05-18
  • 2016-01-08
  • 1970-01-01
  • 1970-01-01
  • 2016-09-13
  • 1970-01-01
相关资源
最近更新 更多