简体   繁体   中英

Formatting a dictionary with Pandas Python

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]
     }

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')

This is a strange question. It seems tailor-made for pandas, but only involves dict s... 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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM