Home > Blockchain >  Formatting a dictionary with Pandas Python
Formatting a dictionary with Pandas Python

Time:12-28

How would I be able to rearrange the values of dictionary a so that it turns into the format of a2. All the columns values will be turned into keys with their corresponding values. How would I be able to get the Expected Output below?

Code:

a = {'columns': ['Month Average',
             'Month Median',
             'Month Max'],
 'data': [[0.0,
           0.0,
           0.0],
          [0.0,
           0.0,
           0.0],
          [-15.15,
           48.55384615384616,
           3.85]],
 'index': [2015, 2016, 2017]}

Expected Output:

a = {
    'index': [2015, 2016, 2017],
    'Month Average':[0.0,0.0,0.0],
    'Month Median': [0.0,0.0,0.0],
    'Month Max': [-15.15,48.55384615384616,3.85]
     }

CodePudding user response:

First non pandas solution:

a2 = {**{'index':a['index']}, **dict(zip(a['columns'], a['data']))}
print (a2)
{'index': [2015, 2016, 2017], 'Month Average': [0.0, 0.0, 0.0], 'Month Median': [0.0, 0.0, 0.0], 'Month Max': [-15.15, 48.55384615384616, 3.85]}

Use DataFrame constructor:

df = pd.DataFrame(a['data'], index=a['index'], columns=a['columns'])
#if only data, index and columns keys use unpack **
df = pd.DataFrame(**a)
print (df)
      Month Average  Month Median  Month Max
2015           0.00      0.000000       0.00
2016           0.00      0.000000       0.00
2017         -15.15     48.553846       3.85

If need index column:

df = pd.DataFrame(**a).reset_index()
print (df)
   index  Month Average  Month Median  Month Max
0   2015           0.00      0.000000       0.00
1   2016           0.00      0.000000       0.00
2   2017         -15.15     48.553846       3.85

Last if need dict:

a2 = df.to_dict(orient='list')

CodePudding user response:

This is a strange question. It seems tailor-made for pandas, but only involves dicts... But you should be able to just do:

pd.DataFrame(**a).reset_index().to_dict(orient="list")

Or, using pure python:

dict(zip(a['columns'], a['data']), index=a['index'])

Not sure why you'd involve pandas here...

  • Related