向 MultiIndex DataFrame 添加新行 [英] Add new rows to a MultiIndex DataFrame

查看:83
本文介绍了向 MultiIndex DataFrame 添加新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定这个多索引数据帧:

Given this MultiIndex Dataframe:

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'])

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

I would like to add a new row (inner index) to every row in the outer index.

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

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

However this gives me an error: KeyError: 'three'

我怎样才能做到这一点?

How can I accomplish this?

行中的所有值相同.

推荐答案

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

<小时>

对此答案的更新,以说明您希望添加特定值.用以下代码片段替换最后一行:


An update to this answer to account for your desire to add specific values. Replace the last line with this code snippet:

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

这篇关于向 MultiIndex DataFrame 添加新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆