JR1
JR1

Reputation: 57

Create MultiIndex Dataframe from Dictionary of Lists

I would like to create an empty, MultiIndex DataFrame where the first level of columns contains the dictionary keys, with the second level of columns containing the values for each key.

Example:

dictionary = {"Col 1": ["foo", "bar"], "Col 2": ["one", "two"]}

enter image description here

Upvotes: 1

Views: 294

Answers (1)

anky
anky

Reputation: 75140

You can flatten the dictionary for each key and value , then use pd.MultiIndex.from_arrays , then swaplevel:

d = {i:k for k,v in dictionary.items() for i in v}
df = (pd.DataFrame(columns=pd.MultiIndex.from_arrays((d.keys(),d.values())))
      .swaplevel(axis=1).rename_axis(columns=['first','second']))

#df.to_excel(...)

enter image description here

Upvotes: 2

Related Questions