【问题标题】:How to add a new row to pandas dataframe with non-unique multi-index如何使用非唯一多索引向熊猫数据框添加新行
【发布时间】:2019-02-24 13:21:52
【问题描述】:
df = pd.DataFrame(np.arange(4*3).reshape(4,3), index=[['a','a','b','b'],[1,2,1,2]], columns=list('xyz'))

df 的样子:

现在我添加一个新行:

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

那么df就变成了:

现在我想做同样的事情,但使用具有非唯一多索引的不同 df:

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

,看起来像:

并调用

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

结果是“异常:无法处理非唯一多索引!”

我怎样才能实现目标?

【问题讨论】:

    标签: pandas multi-index


    【解决方案1】:

    将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
    

    【讨论】:

    • 非常感谢您的大力帮助。我会在 10 分钟后点击接受按钮(系统默认):)
    猜你喜欢
    • 2015-02-22
    • 1970-01-01
    • 2016-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-06
    • 1970-01-01
    • 2021-06-11
    相关资源
    最近更新 更多