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

如何使用非唯一多索引向数据帧添加新行

  •  1
  • Royalblue  · 技术社区  · 7 年前
    df = pd.DataFrame(np.arange(4*3).reshape(4,3), index=[['a','a','b','b'],[1,2,1,2]], columns=list('xyz'))
    

    其中df看起来像:

    enter image description here

    现在我添加一个新行:

    df.loc['new',:]=[0,0,0]
    

    enter image description here

    df = pd.DataFrame(np.arange(4*3).reshape(4,3), index=[['a','a','b','b'],[1,1,2,2]], columns=list('xyz'))
    

    ,看起来像:

    enter image description here

    df.loc['new',:]=[0,0,0]
    

    我怎样才能达到目标?

    1 回复  |  直到 7 年前
        1
  •  1
  •   jezrael    7 年前

    使用 append concat 带助手 DataFrame :

    df1 = pd.DataFrame([[0,0,0]], 
                       columns=df.columns, 
                       index=pd.MultiIndex.from_arrays([['new'], ['']]))
    df2 = df.append(df1)
    
    df2 = pd.concat([df, df1])
    print (df2)
           x   y   z
    a   1  0   1   2
        1  3   4   5
    b   2  6   7   8
        2  9  10  11
    new    0   0   0