Rebin Rebin - 7 months ago 15
Python Question

Non numerical indexing in multidimensional matrices (lists)

Is there any way to create a 2D matrix with NON numerical indexing? and MORE importantly GET/SET the values by using those non numerical indexes?

I mean having a 2D matrix like

mat=
one two three
A 1 2 3
B 4 5 6


and then be able to SET/GET like

>>>m13=mat[A,three]
>>> m13
>>> 3


any idea snippet appreciated. I was thinking of using 'Pandas' but couldnt figure it out.

Answer

You can use loc:

import pandas as pd

mat = pd.DataFrame({'three': {'A': 3, 'B': 6},
                    'two': {'A': 2, 'B': 5}, 
                    'one': {'A': 1, 'B': 4}}, 
                    columns = ['one','two','three'])

print mat
   one  two  three
A    1    2      3
B    4    5      6

#GET
print mat.loc['A', 'three']
3

#SET
mat.loc['A', 'three'] = 10
print mat
   one  two  three
A    1    2     10
B    4    5      6

EDIT:

You can create DataFrame from numpy array too:

print arr
[[1 2 3]
 [4 5 6]]

mat = pd.DataFrame(arr, index=['A','B'], columns=['one','two','three'])
   one  two  three
A    1    2      3
B    4    5      6
Comments