numpy矩阵的映射索引

时间:2018-10-26 13:41:40

标签: python numpy dictionary matrix

我应该如何映射一个numpy矩阵的索引?

例如:

mx = np.matrix([[5,6,2],[3,3,7],[0,1,6]]

行/列索引为0、1、2。

所以:

>>> mx[0,0]
5

假设我需要映射这些索引,将0, 1, 2转换为例如10, 'A', 'B'的使用方式:

mx[10,10] #returns 5
mx[10,'A'] #returns 6 and so on..

我可以只设置一个dict并使用它来访问元素,但是我想知道是否可以做像我刚才描述的那样的事情。

3 个答案:

答案 0 :(得分:3)

我建议将pandas dataframe与索引和列一起使用,并将新映射分别用于行和列索引,以便于建立索引。它使我们可以使用熟悉的colon运算符选择单个元素或整个行或一列。

考虑一个通用(非正方形4x3形状的矩阵)-

mx = np.matrix([[5,6,2],[3,3,7],[0,1,6],[4,5,2]])

考虑行和列的映射-

row_idx = [10, 'A', 'B','C']
col_idx = [10, 'A', 'B']

让我们看一下具有给定样本的工作流程-

# Get data into dataframe with given mappings
In [57]: import pandas as pd

In [58]: df = pd.DataFrame(mx,index=row_idx, columns=col_idx)

# Here's how dataframe data looks like
In [60]: df
Out[60]: 
    10  A  B
10   5  6  2
A    3  3  7
B    0  1  6
C    4  5  2

# Get one scalar element
In [61]: df.loc['C',10]
Out[61]: 4

# Get one entire col
In [63]: df.loc[:,10].values
Out[63]: array([5, 3, 0, 4])

# Get one entire row
In [65]: df.loc['A'].values
Out[65]: array([3, 3, 7])

最重要的是,由于数据帧及其切片仍在索引到原始矩阵/数组存储空间中,因此我们没有做任何额外的副本-

In [98]: np.shares_memory(mx,df.loc[:,10].values)
Out[98]: True

答案 1 :(得分:0)

尝试一下:

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "baseUrl": "./",
    "module": "es6",
    "types": [],
    "paths": {
      "@angular/*": [
        "../node_modules/@angular/*"
      ]
    }
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}

答案 2 :(得分:0)

您可以使用__getitem____setitem__特殊方法并如图所示创建一个新类。 将索引图作为字典存储在实例变量self.index_map中。

import numpy as np

class Matrix(np.matrix):
    def __init__(self, lis):
        self.matrix = np.matrix(lis)
        self.index_map = {}

    def setIndexMap(self, index_map):
        self.index_map = index_map

    def getIndex(self, key):
        if type(key) is slice:
            return key
        elif key not in self.index_map.keys():
            return key
        else:
            return self.index_map[key]

    def __getitem__(self, idx):
        return self.matrix[self.getIndex(idx[0]), self.getIndex(idx[1])]

    def __setitem__(self, idx, value):
        self.matrix[self.getIndex(idx[0]), self.getIndex(idx[1])] = value

用法:

创建矩阵。

>>> mx = Matrix([[5,6,2],[3,3,7],[0,1,6]])
>>> mx
Matrix([[5, 6, 2],
        [3, 3, 7],
        [0, 1, 6]])


定义索引图。

>>> mx.setIndexMap({10:0, 'A':1, 'B':2})


索引矩阵的不同方法。

>>> mx[0,0]
5
>>> mx[10,10]
5
>>> mx[10,'A']
6


它还可以处理切片,如图所示。

>>> mx[1:3, 1:3]
matrix([[3, 7],
        [1, 6]])