簡體   English   中英

Append一級到pandas MultiIndex

[英]Append a level to a pandas MultiIndex

假設我有一個帶有三個索引“a”、“b”和“c”的 pandas dataframe - 如何從數組中添加第四個索引並同時將其名稱設置為“d”?

這有效:

df.set_index(fourth_index, append=True, inplace=True)
df.index.set_names(['a','b','c','d'], inplace=True)

但我正在尋找不需要我再次命名前三個索引的東西,例如(這不起作用):

df.set_index({'d': fourth_index}, append=True, inplace=True)

我在這里錯過了一些 function 嗎?

fourth_index添加為列,然后調用set_index 名稱被保留。

df = df.assign(d=fourth_index).set_index('d', append=True)

請注意,如果您擔心內存不足,則可以按原樣進行。 少犧牲一點字符就毫無意義。


演示

df
          a   b   c   d
l1  l2                 
bar one  24  13   8   9
    two  11  30   7  23
baz one  21  31  12  30
    two   2   5  19  24
foo one  15  18   3  16
    two   2  24  28  11
qux one  23   9   6  12
    two  29  28  11  21

df.assign(l3=1).set_index('l3', append=True)

             a   b   c   d
l1  l2  l3                
bar one 1   24  13   8   9
    two 1   11  30   7  23
baz one 1   21  31  12  30
    two 1    2   5  19  24
foo one 1   15  18   3  16
    two 1    2  24  28  11
qux one 1   23   9   6  12
    two 1   29  28  11  21

為什么不保存之前的先前值的名稱,即

old_names = df.index.names
df.set_index(fourth_index, append=True, inplace=True)
df.index.set_names(old_names + ['d'], inplace=True)

這樣就保留了良好性能的好處,並且不需要您重新鍵入舊名稱。

set_names 支持特定於級別的(重新)命名

df.set_index(fourth_index, append=True, inplace=True)
df.index.set_names('d', level=df.index.nlevels-1, inplace=True)

這應該足夠了:

fourth_index.name = 'd'
df.set_index(fourth_index, append=True, inplace=True)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM