【发布时间】:2014-07-15 18:19:16
【问题描述】:
我经常遇到这样的情况,即我有一个具有以下级别的 pandas 多索引:
ix = pd.MultiIndex.from_tuples(((1, 2),
(1, 3),
(2, 2),
(2, 5)), names=['hi', 'there'])
a = pd.DataFrame([0]*4, index=ix, columns=['foo'])
采用这种结构:
print a
foo
hi there
1 2 0
3 0
2 2 0
5 0
但是,我想扩展这些索引,例如每个级别 3 个新索引。所以我想添加另一个索引,使最终产品看起来像这样:
foo
hi there newix
1 2 1 0
2 0
3 1 0
2 0
2 2 1 0
2 0
5 1 0
2 0
我想不出使用“from_product”之类的明显方法来做到这一点。我想我可以通过迭代前两行来手动构造元组,但这似乎很麻烦。有没有比我想象的更优雅的方法来实现这一点?
编辑:理想情况下,这将是其他的东西,比如说:
newixs = []
for ix in a.index:
for i in range(5):
nix = list(ix) + [i]
newixs.append(nix)
这可行(使用 from_tuples 制作 pandas 多索引),但对我来说似乎很老套:P
【问题讨论】: