1

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

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

What about if the second level column names are the same? E.g. Col 1: "foo", "bar", Col 2: "foo", "bar". This works perfectly except I have some second level names that are getting lost as they repeat.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.