Map index of numpy matrix

Viewed 1706

How should I map indices of a numpy matrix?

For example:

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

The row/column indices are 0, 1, 2.

So:

>>> mx[0,0]
5

Let s say I need to map these indices, converting 0, 1, 2 into, e.g. 10, 'A', 'B' in the way that:

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

I can just set a dict and use it to access the elements, but I would like to know if it is possible to do something like what I just described.

3 Answers

I would suggest using pandas dataframe with the index and columns using the new mapping for row and col indexing respectively for ease in indexing. It allows us to select a single element or an entire row or column with the familiar colon operator.

Consider a generic (non-square 4x3 shaped matrix) -

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

Consider the mappings for rows and columns -

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

Let's take a look on the workflow with the given sample -

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

And best of all we are not making any extra copies as the dataframe and its slices are still indexing into the original matrix/array memory space -

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

Try this:

import numpy as np
A = np.array(((1,2),(3,4),(50,100)))
dt = np.dtype([('ID', np.int32), ('Ring', np.int32)])
B = np.array(list(map(tuple, A)), dtype=dt)
print(B['ID'])

You can use the __getitem__ and __setitem__ special methods and create a new class as shown. Store the index map as a dictionary in an instance variable 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

Usage:

Creating a matrix.

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


Defining the Index Map.

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


Different ways to index the matrix.

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


It also handles slicing as shown.

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