Skip to content Skip to sidebar Skip to footer

Creating A Multiindexed `Series` With A Nested Dictionary

In my mind, what I'm trying to do ought to be straightforward, as straightforward as passing it into the constructor, but in reality it's not. I have a dictionary like below. d = {

Solution 1:

I think you need DataFrame constructor with unstack:

import pandas as pd
import numpy as np

d = {"russell": {"score": np.random.rand(), "ping": np.random.randint(10, 100)},
    "cantor": {"score": np.random.rand(), "ping": np.random.randint(10, 100)},
    "godel": {"score": np.random.rand(), "ping": np.random.randint(10, 100)}}

print (pd.DataFrame(d).unstack())  

cantor   ping     33.000000
         score     0.240253
godel    ping     64.000000
         score     0.435040
russell  ping     41.000000
         score     0.171810
dtype: float64

Also if need swap levels in MultiIndex use stack:

print (pd.DataFrame(d).stack())    
ping   cantor     64.000000
       godel      40.000000
       russell    66.000000
score  cantor      0.265771
       godel       0.283725
       russell     0.085856
dtype: float64

Post a Comment for "Creating A Multiindexed `Series` With A Nested Dictionary"