create dictionaries for combination of columns of a dataframe in pandas

robinhoodjr :

If I have 100 columns in a dataframe and I want to create dictionaries of pair of columns, the key would always be a fixed columns. How can it be done?

Let's say we have a dataframe like this:

k    v1    v2    ...    v99
============================
i    1     2     ...    9
ii   11    22    ...    99
iii  111   222   ...    999
...

I would want dictionaries dict_v1, dict_v2 ... dict_v99. For example dict_v2 would be:

{'i': 2, 'ii': 22, 'iii': 222, ...}
jezrael :

I suggest create dictionary of dictionaries like:

d = df.set_index('k').to_dict()
print (d)
{'v1': {'i': 1, 'ii': 11, 'iii': 111}, 
 'v2': {'i': 2, 'ii': 22, 'iii': 222}, 
 'v99': {'i': 9, 'ii': 99, 'iii': 999}}

Then each dict is possible select by key:

print (d['v2'])
{'i': 2, 'ii': 22, 'iii': 222}

Another idea should be:

df1 = df.set_index('k')
print (df1)
      v1   v2  v99
k                 
i      1    2    9
ii    11   22   99
iii  111  222  999

print (df1['v2'].to_dict())
{'i': 2, 'ii': 22, 'iii': 222}

What you need is possible, but is bad idea to add names dynamically to a Python namespace.:

for k, v in df.set_index('k').to_dict().items():
    globals()[f'dict_{k}'] =  v

print (dict_v2)
{'i': 2, 'ii': 22, 'iii': 222}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=386421&siteId=1