【问题标题】:Add an index column and reindex dataframe by matching partial index lables通过匹配部分索引标签添加索引列并重新索引数据框
【发布时间】:2018-09-08 03:55:40
【问题描述】:

我有一个多索引 df s:

arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
    ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
pd.MultiIndex(levels=[['bar', 'baz', 'foo', 'qux'], ['one', 'two']],
       labels=[[0, 0, 1, 1, 2, 2, 3, 3], [0, 1, 0, 1, 0, 1, 0, 1]],
       names=['first', 'second'])
s = pd.Series(np.random.randn(8), index=index)
s

我想通过匹配索引列“first”和“second”来添加一个新的索引列“zero”,其中 x,y,z 到 s。换句话说,我想重复 s 三次,但是这个附加的索引列带有 x,y,z。我尝试了重新索引(见下文),但为什么它给了我所有的 NaN?

mux=pd.MultiIndex.from_product([["x","y","z"], 
                            s.index.get_level_values(0),
                            s.index.get_level_values(1)],
                           names=["zero","first", "second"])
t=s.reindex(mux)
t

我也尝试将匹配级别指定为“第一”和“第二”,但看起来级别只需要一个整数?

【问题讨论】:

    标签: python pandas multi-index reindex


    【解决方案1】:

    您可以使用reindex,但必须通过levels 创建MultiIndex。但它会将新级别附加到现有级别,因此如有必要添加reorder_levelssort_index

    np.random.seed(123)
    arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
        ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
    tuples = list(zip(*arrays))
    index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
    
    s = pd.Series(np.random.randn(8), index=index)
    #print (s)
    

    mux=pd.MultiIndex.from_product([s.index.levels[0],s.index.levels[1], ["x","y","z"]])
    t=s.reindex(mux, method='ffill').reorder_levels([2,0,1]).sort_index()
    print (t)
    x  bar  one   -1.085631
            two    0.997345
       baz  one    0.282978
            two   -1.506295
       foo  one   -0.578600
            two    1.651437
       qux  one   -2.426679
            two   -0.428913
    y  bar  one   -1.085631
            two    0.997345
       baz  one    0.282978
            two   -1.506295
       foo  one   -0.578600
            two    1.651437
       qux  one   -2.426679
            two   -0.428913
    z  bar  one   -1.085631
            two    0.997345
       baz  one    0.282978
            two   -1.506295
       foo  one   -0.578600
            two    1.651437
       qux  one   -2.426679
            two   -0.428913
    dtype: float64
    

    【讨论】:

    • @cᴏʟᴅsᴘᴇᴇᴅ - 我将其更改为第一级
    • @cᴏʟᴅsᴘᴇᴇᴅ - 谢谢。并祝贺新工作:)
    • 谢谢,你总是这么快地回答我所有的问题:) 你的回答真的是我的问题:为什么重新索引不起作用,但其他方法似乎更容易。
    • ...我对 StackOverflow 很陌生,不知道该功能:P
    【解决方案2】:

    IIUC,你想要pd.concat

    s = pd.concat([s] * 3, axis=0, keys=['x', 'y', 'z'])
    

    如果需要,重命名轴:

    s = s.rename_axis(['zero', 'first', 'second'])
    

    s 
    
    zero  first  second
    x     bar    one       0.510567
                 two       0.066620
          baz    one       0.667948
                 two      -1.471894
          foo    one       1.881198
                 two       0.143628
          qux    one       1.108174
                 two      -0.978112
    y     bar    one       0.510567
                 two       0.066620
          baz    one       0.667948
                 two      -1.471894
          foo    one       1.881198
                 two       0.143628
          qux    one       1.108174
                 two      -0.978112
    z     bar    one       0.510567
                 two       0.066620
          baz    one       0.667948
                 two      -1.471894
          foo    one       1.881198
                 two       0.143628
          qux    one       1.108174
                 two      -0.978112
    dtype: float64
    

    【讨论】:

    • 是的,这绝对是实现我想要的更简单的方法。谢谢。
    • @edge27 没问题,jezrael 的回答也不错,所以即使您只能接受一个答案,您也可以投票赞成所有答案。干杯。
    猜你喜欢
    • 2018-08-24
    • 2016-09-02
    • 1970-01-01
    • 2020-04-16
    • 2020-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多