Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a nice matrix from a dictionary

I would like to make a matrix that makes a list of nested dictionaries. But I can't find out how to make a matrix, end even less how to put my values into it.

My dictionary looks like:

    {'1': {'3': 0, '2': 1, '5': 1, '4': 0, '6': 29},
    '3': {'1': 0, '2': 0, '5': 0, '4': 1, '6': 1},
    '2': {'1': 13, '3': 1, '5': 21, '4': 0, '6': 0},
    '5': {'1': 39, '3': 0, '2': 1, '4': 0, '6': 14},
    '4': {'1': 1, '3': 1, '2': 17, '5': 2, '6': 0},
    '6': {'1': 0, '3': 43, '2': 0, '5': 0, '4': 1}}

and it should be ordered in a matrix so it looks like this:

        1  2  3  4   5   6
     1  -  1  0  0   1   29
     2  13 -  1  0   21  0
     3  0  0  -  1   0   1
     4  1  17 1  -   2   0
     5  39 1  0  0   -   14
     6  0  0  43 1   0   -

I have only tried to understand how to make a matrix:

    table=[[for 0 in range(6)] for j in range[6]]
    print table
    for d1 in range(6):
        for d2 in range(6):
            table[d1][d2]=d1+d2+2
    print table

But I have a dictionary, not lists. I am really lost.

like image 630
anne Avatar asked Jan 03 '13 12:01

anne


1 Answers

importpandasas pd

a = pd.DataFrame({'1': {'3': 0, '2': 1, '5': 1, '4': 0, '6': 29},
                  '3': {'1': 0, '2': 0, '5': 0, '4': 1, '6': 1},
                  '2': {'1': 13, '3': 1, '5': 21, '4': 0, '6': 0},
                  '5': {'1': 39, '3': 0, '2': 1, '4': 0, '6': 14},
                  '4': {'1': 1, '3': 1, '2': 17, '5': 2, '6': 0},
                  '6': {'1': 0, '3': 43, '2': 0, '5': 0, '4': 1}})

puts into a:

    1   2   3   4   5   6
1 NaN  13   0   1  39   0
2   1 NaN   0  17   1   0
3   0   1 NaN   1   0  43
4   0   0   1 NaN   0   1
5   1  21   0   2 NaN   0
6  29   0   1   0  14 NaN

which can be then printed into your format:

print a.to_string(na_rep='-')

printing:

    1   2   3  4   5   6
1   -   1   0  0   1  29
2  13   -   1  0  21   0
3   0   0   -  1   0   1
4   1  17   1  -   2   0
5  39   1   0  0   -  14
6   0   0  43  1   0   -
like image 181
eumiro Avatar answered Oct 26 '22 16:10

eumiro