Skip to content
Advertisement

How to create dataframe and set index with dictionary of dictionaries?

I want to create a Dataframe with the columns as the Days of the week, and each person’s name and corresponding start/end times. So far I can get the data from the dictionary to the Dataframe, but I am struggling to get the index correct. I managed to get a bit of help from this question Python – how to load nested dictionary into Pandas dataframe?, but I’m not sure how to rearange the indexes to achieve what I need.

I know I need to .drop the Times column altogether, but after that I am coming up short of ideas. I’m thinking somehow set row[0] as the index, but I’m unsure if that would be the best way to do this.

Here’s what I’ve got working so far:

data:

JavaScript

code to create the dataframe:

JavaScript

current output:

JavaScript

required output:

JavaScript

Advertisement

Answer

There isn’t a column equivalent to set_index, so you can create a DataFrame from each sub-dictionary and then Transpose and concat them together in the end. You can then assign the key as the day value.

In the end if you want a MultiIndex just .set_index(['Days', 'Times'])

JavaScript

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement