2

I want to convert a Pandas DataFrame into separate dicts, where the names of the dict are the columnn names and all dics have the same index.

the dataframe looks like this:

            cBmsExp  cCncC  cDnsWd  
PlantName                                                 
A.gre          2.5   0.45   896.8  
A.rig          2.5   0.40   974.9  
A.tex          3.5   0.45   863.1    

the result should be:

cBmsExp = {"A.gre":2.5, "A.rig": 2.5, "A.tex": 3.5}
cCncC   = {"A.gre":0.45, "A.rig": 0.4, "A.tex": 0.45}
cDnsWd  = {"A.gre":898.8, "A.rig": 974.9, "A.tex": 863.1}

I can't figure out how a column name can become the name of a variable in my Python code.

I went through piles of stack overflow questions and answers, but I didn't find this type of problem among them.

Suggestions for code are very much appreciated!

koen
  • 23
  • 3

1 Answers1

3

It is not recommended, better is create dict of dicts and select by keys:

d = df.to_dict()
print (d)
{'cBmsExp': {'A.gre': 2.5, 'A.rig': 2.5, 'A.tex': 3.5},
 'cCncC': {'A.gre': 0.45, 'A.rig': 0.4, 'A.tex': 0.45}, 
 'cDnsWd': {'A.gre': 896.8, 'A.rig': 974.9, 'A.tex': 863.1}}

print (d['cBmsExp'])
{'A.gre': 2.5, 'A.rig': 2.5, 'A.tex': 3.5}

But possible, e.g. by globals:

for k, v in d.items():
 globals()[k] =  v

print (cBmsExp)
{'A.gre': 2.5, 'A.rig': 2.5, 'A.tex': 3.5}
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252