【问题标题】:python numpy array / dict multiple inheritancepython numpy数组/dict多重继承
【发布时间】:2012-02-12 17:13:31
【问题描述】:

我想知道是否有一种简单的方法可以创建一个类来处理 numpy 数字数组的整数和关键字索引。

最终目标是拥有一个 numpy 数组,我还可以使用每个变量的名称对其进行索引。 例如,如果我有列表

import numpy as np
a = [0,1,2,3,4]
names = ['name0','name1','name2','name3','name4']
A = np.array(a)

我希望能够通过调用(例如)A['name1'] 轻松获取 A 的值,但让数组保留 numpy 数组的所有功能。

谢谢!

彼得

编辑:

非常感谢您的帮助,我会尽量明确预期用途!我有一组现有的代码,它使用 numpy 数组来存储和应用变量向量。我的向量有大约 30 个条目。

当我想查看特定变量的值时,或者当我想对其中一个变量进行更改时,我必须记住哪个条目对应于哪个变量(条目的顺序或数量不一定会改变一旦创建了数组)。现在我用字典来跟踪。例如,我有一个具有 30 个值的 numpy 数组“VarVector”。 “vmax”是条目 15,值为 0.432。然后我将有一个包含 30 个键 'VarDict' 的并发字典,这样 VarDict[entry] = index.这样我可以通过链接调用找到 vmax 的值

VarVector[VarDict["vmax"]]

这将返回 0.432

我想知道是否有一种简单地组合这两个结构的好方法,这样 VarVector[15](为了兼容性)和 VarVector["vmax"](为了方便我)都会指向同一个数字.

谢谢! 彼得

【问题讨论】:

  • numpy 数组的重点是它们是用 C 语言编写的,因此速度很快。如果你这样做,你将失去 numpy 数组的好处——你还不如使用 Python 列表!
  • 你能给出一个为什么你想这样做的理由吗?
  • @katrielalex - 不一定... numpy 数组的__getitem__ 已经很慢了。通过将其添加到其中,您不会显着减慢速度。但是,这是一个相当常见的用例,并且已经完成了几次(pandaslarry)。看看这个比较:scipy.org/StatisticalDataStructures 在某些情况下,拥有“标记轴”或“标记项目”是一件好事。
  • 很公平,我的立场是正确的。谢谢=)

标签: python arrays dictionary numpy multiple-inheritance


【解决方案1】:

根据您的描述,听起来您只想要一个structured array(numpy 内置)。例如

# Let's suppose we have 30 observations with 5 variables each...
# The five variables are temp, pressure, x-velocity, y-velocity, and z-velocity
x = np.random.random((30, 5))

# Make a structured dtype to represent our variables...
dtype=dict(names=['temp', 'pressure', 'x_vel', 'y_vel', 'z_vel'],
           formats=5 * [np.float])

# Now view "x" as a structured array with the dtype we created...
data = x.view(dtype)

# Each measurement will now have the name fields we created...
print data[0]
print data[0]['temp']

# If we want, say, all the "temp" measurements:
print data['temp']

# Or all of the "temp" and "x_vel" measurements:
print data[['temp', 'x_vel']]

还可以查看rec arrays。它们稍微灵活一些,但速度要慢得多。

data = np.rec.fromarrays(*x, 
              names=['temp', 'pressure', 'x_vel', 'y_vel', 'z_vel'])
print data.temp

但是,您很快就会遇到这两种方法的限制(即您可以命名两个轴)。在这种情况下,如果您只想标记项目,请查看larry,或者如果您想要具有大量缺失值处理的标记数组,请查看pandas

【讨论】:

    【解决方案2】:

    您可以继承 ndarray 并覆盖相关方法(即__getitem____setitem__、...)。 More info here。这类似于@Joe 的答案,但它的优点是它几乎保留了 ndarray 的所有功能。你显然不能再做以下事情了:

    In [25]: array = np.empty(3, dtype=[('char', '|S1'), ('int', np.int)])
    
    In [26]: array['int'] = [0, 1, 2]
    
    In [27]: array['char'] = ['a', 'b', 'c']
    
    In [28]: array
    Out[28]: 
    array([('a', 0), ('b', 1), ('c', 2)], 
          dtype=[('char', '|S1'), ('int', '<i8')])
    
    In [29]: array['char']
    Out[29]: 
    array(['a', 'b', 'c'], 
          dtype='|S1')
    
    In [30]: array['int']
    Out[30]: array([0, 1, 2])
    

    如果我们知道您为什么要这样做,我们也许可以给出更详细的答案。

    【讨论】:

      【解决方案3】:

      我没有对此进行测试,但它应该可以工作。

      我们的想法是假设输入是一个 int 并将其用于 numpy 数组,如果不是,则将其用于 dict。

      import numbers
      import numpy
      
      class ThingArray:
          def __init__(self):
              self.numpy_array = numpy.array()
              self.other_array = dict()
      
          def __setitem__(self, key, value):
              if isinstance(key, numbers.Integral):
                  self.numpy_array[key] = value
              else:
                  self.other_array[key] = value
      
          def __getitem__(self, key):
              if isinstance(key, numbers.Integral):
                  return self.numpy_array[key]
              else:
                  return self.other_array[key]
      
      
      thing = ThingArray()
      
      thing[1] = 100
      thing["one"] = "hundred"        
      
      print thing[1]
      print thing["one"]
      

      【讨论】:

        猜你喜欢
        • 2020-12-18
        • 2021-08-05
        • 1970-01-01
        • 2021-05-16
        • 2015-05-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多