【问题标题】:Add new rows to a MultiIndex DataFrame向 MultiIndex DataFrame 添加新行
【发布时间】:2019-04-28 15:25:21
【问题描述】:

鉴于此 MultiIndex 数据框:

arrays = [np.array(['A', 'A', 'B', 'B', 'C', 'C']),
         np.array(['one', 'two', 'one', 'two', 'one', 'two'])]
df = pd.DataFrame(np.random.randn(6), index=arrays, columns=['col1'])

我想为外部索引中的每一行添加一个新行(内部索引)。

df.loc[(slice(None),'three'),:] = {'A':3, 'B':4, 'C':5}

但是这给了我一个错误: KeyError:'三个'

我怎样才能做到这一点?

编辑:该行中的所有值相同。

【问题讨论】:

    标签: python python-3.x pandas indexing multi-index


    【解决方案1】:

    MultiIndex.from_product + reindex

    a, b = df.index.levels
    
    res = df.reindex(pd.MultiIndex.from_product([a, [*b, 'three']]))
    res[res.index.get_level_values(1) == 'three'] = 3
    

                 col1
    A one   -1.011201
      two    0.376914
      three  3.000000
    B one    0.465666
      two   -0.634804
      three  3.000000
    C one   -0.348338
      two    1.295683
      three  3.000000
    

    对此答案的更新,以说明您希望添加特定值。用这段代码sn-p替换最后一行:

    d = {'A':3, 'B':4, 'C':5}
    s = res.index.get_level_values(0).map(d)
    res.col1.where(res.col1.notnull(), s.values)
    

    A  one     -2.542087
       two      0.966193
       three    3.000000
    B  one     -0.126671
       two      0.864258
       three    4.000000
    C  one      0.063544
       two     -0.401936
       three    5.000000
    Name: col1, dtype: float64
    

    【讨论】:

    • 为了清楚起见,我编辑了这个问题。这并不能完全解决问题,因为它在所有行中都放置了相同的值 (3)。
    • @apkul 更新了我的答案以演示如何映射自定义值
    【解决方案2】:

    可能很冗长,但您可以构造一个新的数据框,连接,然后按索引排序:

    idx = pd.MultiIndex.from_tuples([(i, 'three') for i in df.index.levels[0]])
    df_new = pd.DataFrame(3, index=idx, columns=df.columns)
    
    df = pd.concat([df, df_new]).sort_index()
    
    print(df)
    
                 col1
    A one   -0.810362
      three  3.000000
      two    0.014020
    B one    0.700392
      three  3.000000
      two    0.189968
    C one   -1.214194
      three  3.000000
      two    1.199316
    

    【讨论】:

      【解决方案3】:

      使用concat

      s=pd.Series({'A':3, 'B':4, 'C':5}).to_frame('col1').assign(index='three')
      pd.concat([df,s.set_index('index',append=True)]).sort_index(level=0)
      Out[205]: 
                   col1
      A one    0.529647
        three  3.000000
        two   -1.763707
      B one   -0.673773
        three  4.000000
        two   -0.706385
      C one    1.105963
        three  5.000000
        two    1.291009
      

      【讨论】:

        猜你喜欢
        • 2014-09-15
        • 2018-08-20
        • 1970-01-01
        • 2021-06-16
        • 2016-12-30
        • 2019-04-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多