Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping dictionary with multiple key values to data frame

Tags:

python

pandas

I have a dictionary which has multiple key values.

d = {(0, 0, 'Shift 2 (2000 FT)'): 0.0, (0, 0, 'Shift 1 (0800 FT)'): 0.0, (0, 1, 'Shift 2 (2000 FT)'): 0.0, (0, 1, 'Shift 1 (0800 FT)'): 0.0, (0, 2, 'Shift 2 (2000 FT)'): 0.0, (0, 2, 'Shift 1 (0800 FT)'): 0.0}

I want to convert it to dataframe as follows where the first index is called 'WEEK', second called 'DAY' and the third goes to columns.

enter image description here

Please advise. Thanks!

like image 640
user3388437 Avatar asked May 06 '26 04:05

user3388437


2 Answers

You can read in the dict then turn the Index into a MultiIndex and reshape.

import pandas as pd

df = pd.DataFrame.from_dict(d, orient='index')
df.index = pd.MultiIndex.from_tuples(df.index)

df = (df[0].unstack(-1)
           .rename_axis(index=['Week', 'Day'])
           .reset_index())

   Week  Day  Shift 1 (0800 FT)  Shift 2 (2000 FT)
0     0    0                0.0                0.0
1     0    1                0.0                0.0
2     0    2                0.0                0.0

You can also create the initial DataFrame with the MultiIndex in one go with the normal constructor. Then do the unstacking.

df = pd.DataFrame(data=d.values(), index=d.keys())
like image 112
ALollz Avatar answered May 08 '26 16:05

ALollz


Another option : create a flat list of list and then use pivot_table.

from itertools import chain
df = pd.DataFrame([list(chain(*[list(key),[val]])) for key,val in d.items()])
df = df.pivot_table(index=[0,1], columns=2).reset_index()
df.columns = ['Week','Day','Shift 1 (0800 FT)','Shift 2 (2000 FT)']
like image 40
Nk03 Avatar answered May 08 '26 16:05

Nk03



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!