Oli*_*Oli 6 python indexing multi-index pandas
假设我有一个带有三个索引“a”、“b”和“c”的 Pandas 数据框 - 如何从数组中添加第四个索引并同时将其名称设置为“d”?
这有效:
df.set_index(fourth_index, append=True, inplace=True)
df.index.set_names(['a','b','c','d'], inplace=True)
Run Code Online (Sandbox Code Playgroud)
但是我正在寻找不需要我再次命名前三个索引的东西,例如(这不起作用):
df.set_index({'d': fourth_index}, append=True, inplace=True)
Run Code Online (Sandbox Code Playgroud)
我在这里错过了一些功能吗?
添加fourth_index
为列,然后调用set_index
. 名称被保留。
df = df.assign(d=fourth_index).set_index('d', append=True)
Run Code Online (Sandbox Code Playgroud)
请注意,如果您担心内存,那么您所做的一切都很好。为了更少的字符而牺牲性能是没有意义的。
演示
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
Run Code Online (Sandbox Code Playgroud)