python numpy array/dict 多重继承

标签 python arrays dictionary numpy multiple-inheritance

我想知道是否有一种简单的方法可以创建一个类来处理 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"](为了方便我)都指向相同的数字.

谢谢! 彼得

最佳答案

根据您的描述,听起来您只想要一个 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如果您希望标记数组具有很多不错的缺失值处理。

关于python numpy array/dict 多重继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8902432/

相关文章:

python - 仅提取特定子文件夹 7zip

Mac OS X Lion 上的 Python MySQL

python - 安装 debian/control 文件的依赖项

c - 如何正确定义常量值的多个结构的常量数组?

python - Python中的按键错误4

python - openpyxl:从 Excel 中丢失精度读数 float ?

javascript求和多维数组

javascript - 在 p5.js 中遍历 JSON 数组

c++ - 在 header 中添加 typedef 时出错

java - android字典int,Imageview