How to convert pandas dataframe to hierarchical dictionary

You can do the following,

df2 = df1.groupby(['date', 'blockcount']).agg(lambda x: pd.Series(x).tolist())

# Formatting the result to the correct format
dct = {}
for k, v in df2["reactiontime"].items():
  if k[0] not in dct: 
    dct[k[0]] = {}
  dct[k[0]].update({k[1]: v})

Which produces,

>>> {200101: {1: [350, 400], 2: [200, 250]}, 200102: {1: [100, 300], 2: [450, 400]}}

dct holds the result you need.


Here is another way using pivot_table:

d = df1.pivot_table(index='blockcount',columns='date',
     values='reactiontime',aggfunc=list).to_dict()

print(d)

{200101: {1: [350, 400], 2: [200, 250]},
 200102: {1: [100, 300], 2: [450, 400]}}

IIUC

    df1.groupby(['date','blockcount']).reactiontime.agg(list).unstack(0).to_dict()
{200101: {1: [350, 400], 2: [200, 250]}, 200102: {1: [100, 300], 2: [450, 400]}}

Tags:

Python

Pandas