代码之家  ›  专栏  ›  技术社区  ›  user48956

如何分配到大熊猫的新行。多索引系列?

  •  0
  • user48956  · 技术社区  · 6 年前

    我过去可以分配给这样的序列:

    import pandas as pd
    pd.Series()["aaa"]= True        # regular indexing
    pd.Series().loc["aaa"]= True        # regular indexing
    pd.Series()[("aaa",123)]= True  # Multi indexing
    pd.Series().loc[("aaa",123)]= True  # Multi indexing
    

    但在24.0及以上的熊猫中,这两种情况都是:

    pd.Series()[("aaa",123)]= True
    pd.Series().loc[("aaa",123)]= True
    

    给我:

    KeyError: u"None of [Index([u'aaa', 1], dtype='object')] are in the [index]"
    

    那么--如何在熊猫0.24.1中使用多索引分配给一个系列?

    1 回复  |  直到 6 年前
        1
  •  1
  •   ALollz    6 年前

    首先初始化空的 MultiIndex 正确的尺寸,然后工作:

    import pandas as pd
    
    idx = pd.MultiIndex(levels=[[], []], codes=[[], []])
    s = pd.Series(index=idx)
    s.loc[("aaa",123)]= True
    
    print(s)
    #aaa  123    True
    #dtype: bool