Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将元数据注释添加到Numpy ndarray_Python_Arrays_Numpy - Fatal编程技术网

Python 将元数据注释添加到Numpy ndarray

Python 将元数据注释添加到Numpy ndarray,python,arrays,numpy,Python,Arrays,Numpy,我有一个由三个大数组组成的Numpy ndarray,我只想将生成数据的文件的路径存储在其中的某个地方。一些玩具数据: A = array([[ 6.52479351e-01, 6.54686928e-01, 6.56884432e-01, ..., 2.55901861e+00, 2.56199503e+00, 2.56498647e+00], [ nan, nan, 9.

我有一个由三个大数组组成的Numpy ndarray,我只想将生成数据的文件的路径存储在其中的某个地方。一些玩具数据:

A = array([[  6.52479351e-01,   6.54686928e-01,   6.56884432e-01, ...,
              2.55901861e+00,   2.56199503e+00,   2.56498647e+00],
           [             nan,              nan,   9.37914686e-17, ...,
              1.01366425e-16,   3.20371075e-16,  -6.33655223e-17],
           [             nan,              nan,   8.52057308e-17, ...,
              4.26943463e-16,   1.51422386e-16,   1.55097437e-16]],                 
           dtype=float32)
我不能将它作为数组附加到ndarray,因为它需要与其他三个数组的长度相同

我可以添加
np.zero(len(A[0])
并将第一个值作为字符串,这样我就可以用[-1][0]来检索它,但这似乎很荒谬

是否有一些元数据键可以用来存储字符串,比如
/Documents/Data/foobar.txt'
,这样我就可以用
a.metadata.comment
之类的东西来检索它


谢谢

TobiasR的注释是最简单的方法,但您也可以将ndarray子类化。看到或

用法示例:

>>> a = MetaArray([1,2,3], comment='/Documents/Data/foobar.txt')
>>> a.metadata
{'comment': '/Documents/Data/foobar.txt'}

听起来您可能对以持久的方式将元数据与数组一起存储感兴趣。如果是这样,HDF5是用作存储容器的最佳选择

例如,让我们创建一个数组,并使用
h5py
将其保存到包含一些元数据的HDF文件中:

import numpy as np
import h5py

some_data = np.random.random((100, 100))

with h5py.File('data.hdf', 'w') as outfile:
    dataset = outfile.create_dataset('my data', data=some_data)

    dataset.attrs['an arbitrary key'] = 'arbitrary values'
    dataset.attrs['foo'] = 10.2
然后我们可以在以下内容中重新阅读:

import h5py

with h5py.File('data.hdf', 'r') as infile:
    dataset = infile['my data']
    some_data = dataset[...] # Load it into memory. Could also slice a subset.

    print dataset.attrs['an arbitrary key']
    print dataset.attrs['foo']
正如其他人提到的,如果您只关心在内存中存储数据+元数据,那么更好的选择是
dict
或简单包装类。例如:

class Container:
    def __init__(self, data, **kwargs):
        self.data = data
        self.metadata = kwargs
import scipy.signal
import numpy as np

class SeismicCube(object):
    def __init__(self, data, bounds, metadata=None):
        self.data = data
        self.x0, self.x1, self.y0, self.y1, self.z0, self.z1= bounds
        self.bounds = bounds
        self.metadata = {} if metadata is None else metadata

    def inside(self, x, y, z):
        """Test if a point is inside the cube."""
        inx = self.x0 >= x >= self.x1
        iny = self.y0 >= y >= self.y1
        inz = self.z0 >= z >= self.z1
        return inx and iny and inz

    def inst_amp(self):
        """Calculate instantaneous amplitude and return a new SeismicCube."""
        hilb = scipy.signal.hilbert(self.data, axis=2)
        data = np.hypot(hilb.real, hilb.imag)
        return type(self)(data, self.bounds, self.metadata)
当然,这不会直接表现为numpy数组,但是将
ndarrays子类化通常是个坏主意。(可以,但很容易出错。设计一个将数组存储为属性的类几乎总是更好的选择。)

更好的方法是,使用与上述示例类似的类方法进行任何操作。例如:

class Container:
    def __init__(self, data, **kwargs):
        self.data = data
        self.metadata = kwargs
import scipy.signal
import numpy as np

class SeismicCube(object):
    def __init__(self, data, bounds, metadata=None):
        self.data = data
        self.x0, self.x1, self.y0, self.y1, self.z0, self.z1= bounds
        self.bounds = bounds
        self.metadata = {} if metadata is None else metadata

    def inside(self, x, y, z):
        """Test if a point is inside the cube."""
        inx = self.x0 >= x >= self.x1
        iny = self.y0 >= y >= self.y1
        inz = self.z0 >= z >= self.z1
        return inx and iny and inz

    def inst_amp(self):
        """Calculate instantaneous amplitude and return a new SeismicCube."""
        hilb = scipy.signal.hilbert(self.data, axis=2)
        data = np.hypot(hilb.real, hilb.imag)
        return type(self)(data, self.bounds, self.metadata)

您可以将A放入字典中,其中数据字段指向A,注释字段指向您的注释。在各种操作中使用
A
时,是否希望携带此元数据,无论是
C=A+B
A1=A[2,:]
A2=A.copy()
?研究
masked_数组
代码,了解如何将额外数据添加到数组中。这是可能的,但并不简单。不幸的是,此元数据不会通过任何创建副本的函数传播,就像
scipy.ndimage
中的函数一样。但我不确定是否有一个好的解决方案。不幸的是,这没有通过
numpy.isscalar()
检查,因为
isinstance(obj,generic)
、ScalarType中的
type(obj)或
isinstance(或numbers.Number)
都不是
True
。有没有办法伪造这个数组,使其本身成为一个
np.ndarray
?子类化
\uuuu类\uuuuu
不起作用。