jim jarnac
jim jarnac

Reputation: 5152

Python Pandas: Construct a DataFrame with MultiIndex and Dict

I have dict that I would like to turn into a DataFrame with MultiIndex. The dict is:

dikt = {'bloomberg': Timestamp('2009-01-26 10:00:00'),
 'investingcom': Timestamp('2009-01-01 09:00:00')}

I construct a MultiIndex such as follow:

MI= MultiIndex(levels=[['Existing Home Sales MoM'], ['investingcom', 'bloomberg']],
           labels=[[0, 0], [0, 1]],
           names=['indicator', 'source'])

Then a DataFrame as such:

df = pd.DataFrame(index = MI, columns=["datetime"],data =np.full((2,1),np.NaN))

Then lastly I fill the df with data stored in a dict such :

for key in ['indicator', 'source']:
    df.loc[('Existing Home Sales MoM',key), "datetime"] = dikt[key]

and get the expected result:

enter image description here

But would there be a more concise way of doing so by passing the dikt directly into the construction of the df such as

df = pd.DataFrame(index = MI, columns=["datetime"],data =dikt)

so as to combine the 2 last steps in 1?

Upvotes: 0

Views: 229

Answers (1)

IanS
IanS

Reputation: 16241

You can create a datframe from a dictionary using from_dict:

pd.DataFrame.from_dict(dikt, orient='index')

                               0
bloomberg    2009-01-26 10:00:00
investingcom 2009-01-01 09:00:00

You can chain the column and index definitions to get the result you're after in 1 step:

pd.DataFrame.from_dict(dikt, orient='index') \
            .rename(columns={0: 'datetime'}) \
            .set_index(MI)

Upvotes: 2

Related Questions