Pandas MultiIndex JSON¶
In [1]:
import pandas as pd
import numpy as np
import json
DataFrame From Dictionary¶
In [2]:
d = {}
for i in range(2):
for j,k in enumerate(np.random.rand(2)):
d[(i,j)] = {'data1':k, 'data2':np.square(k), 'data3':np.sqrt(k), 'data4':np.log(k)}
In [3]:
d
Out[3]:
In [4]:
df = pd.DataFrame.from_dict(d, orient='index')
In [5]:
df.index.names = ['category1', 'category2']
In [6]:
df
Out[6]:
Alternatively, we could have done the reverse, by making columns the multindex.
In [7]:
df2 = pd.DataFrame.from_dict(d, orient='columns')
In [8]:
df2.columns.names = ['category1', 'category2']
In [9]:
df2
Out[9]:
Dictionary From DataFrame¶
In [10]:
d = df.to_dict()
In [11]:
d
Out[11]:
To get back to original format we had, first transpose, then convert to dictionary.
In [12]:
d = df.T.to_dict()
Of course, since df2 is in fact the "Transpose" of df, doing df2.to_dict()
would be the same as the above method.
In [13]:
d
Out[13]:
Write JSON File¶
JSON only support string
keys
, and therefore won't accept our tuple
from Pandas multiindex
. Converting it to a string would work, and below is a full example on how to do this, however, you should probably consider writing as a simply csv
.
In [14]:
d = {str(k):v for k,v in d.items()}
In [15]:
d
Out[15]:
In [16]:
with open('file.json', 'w') as f:
f.write(json.dumps(d, indent=4))
Read JSON File¶
In [17]:
from ast import literal_eval
In [18]:
with open('file.json') as f:
d = json.loads(f.read())
In [19]:
d = {literal_eval(k):v for k,v in d.items()}
In [20]:
d
Out[20]: