![](/img/trans.png)
[英]Pandas: Collapse a mxn multi-index dataframe into a series by repeating each row index n times
[英]Expand a pandas multi-index with N new levels for each index?
我經常遇到這樣的情況,我有一個 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 來制作熊貓多索引),但對我來說似乎很糟糕:P
我會首先使用 concat 創建一個更大的 DataFrame:
In [11]: res = pd.concat([a, a])
In [12]: res
Out[12]:
foo
hi there
1 2 0
3 0
2 2 0
5 0
1 2 0
3 0
2 2 0
5 0
我認為附加新索引的最簡單方法是添加一個新列,然后set_index
:
In [13]: res['newix'] = np.repeat([1, 2], len(a))
In [14]: res
Out[14]:
foo newix
hi there
1 2 0 1
3 0 1
2 2 0 1
5 0 1
1 2 0 2
3 0 2
2 2 0 2
5 0 2
In [15]: res.set_index('newix', append=True)
Out[15]:
foo
hi there newix
1 2 1 0
3 1 0
2 2 1 0
5 1 0
1 2 2 0
3 2 0
2 2 2 0
5 2 0
這基本上就是你想要的(如果需要,你可以res.sort_index()
)。
您可以簡單地在目標索引 ix3 上使用重新索引(使用隱式廣播):
ix3 = pd.MultiIndex.from_tuples(
[(1, 2, 1), (1, 2, 2),
(1, 3, 1), (1, 3, 2),
(2, 2, 1), (2, 2, 2),
(2, 5, 1), (2, 5, 2)],
names=['hi', 'there', 'newix'])
a.reindex(ix3)
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.