Anas Bouayed Anas Bouayed - 1 month ago 24
Python Question

double layer key in data frame python

I need to create a data frame in python which has double key, each key will have 3 subkeys, so to call a value in the data frame i'll need to refer to it with 3 indexes

df=[ key1 key2 key3
index key11 key12 key13 key21 key22 key23 key31 key32 key33
0 12 32 45 345 34 43 3 54 134
1 143 41 14 4 1 13 14 41 43
2 114 11 54 11 13 13 43 13 13
]


so to call the '11' in column 2 row 3 it should look like df[2,'key1','key12'].
is there any possibility to do so?
Thank you

Answer

You could quite easily set this up with embedded dictionaries and a list. For example:

df = {
    'key1' : {
        'key11' : [12, 143, 114],
        'key12' : [32, 41, 14],
        'key13' : [114, 11, 54]},
    'key2' : {
        'key21' : [345, 4, 11],
        'key22' : [34, 1, 13],
        'key23' : [43, 13, 13]},
    'key3' : {
        'key31' : [3, 14, 43],
        'key32' : [54, 41, 13],
        'key33' : [134, 43, 13]}
    }

The value that you want would then be df['key1']['key12'][2]. This dictionary could be set up automatically with more info on how your data was coming in.