【问题标题】:Creating a multiindexed `Series` with a nested dictionary使用嵌套字典创建多索引“系列”
【发布时间】:2017-03-08 17:54:26
【问题描述】:

在我看来,我想做的事情应该是直截了当的,就像将它传递给构造函数一样直截了当,但实际上并非如此。我有一本像下面这样的字典。

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

我想做类似pandas.Series(d) 的事情并获得一个Series 实例,如下所示。

russell  score  0.87391482
         ping   23
cantor   score  0.77821932
         ping   16
godel    score  0.53372128
         ping   35

但我实际得到的是下面。

cantor     {'ping': 44, 'score': 0.007408727109865398}
godel        {'ping': 41, 'score': 0.9338940910283948}
russell       {'ping': 74, 'score': 0.733817307366666}

有没有办法实现我想要实现的目标?

【问题讨论】:

    标签: python pandas dictionary nested series


    【解决方案1】:

    我认为你需要DataFrame 构造函数和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
    

    如果需要MultiIndex 中的交换级别,请使用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
    

    【讨论】:

      猜你喜欢
      • 2017-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-24
      • 2021-02-04
      • 1970-01-01
      • 2021-04-04
      • 1970-01-01
      相关资源
      最近更新 更多