如何从现有的多索引列 df 设置多索引列
How to set multiindex column from existing multiindex column df
objective 是在 Pandas 中现有的多索引列之上添加另一个多索引。
我的印象是这可以实现如下
# Assuming we have an existing multilevel index as below
df.columns = pd.MultiIndex.from_product([['level1'],['level2'],df.columns ])
# Along the pipeline, we would like to append another multiindex on top of it
df.columns = pd.MultiIndex.from_product([['Top'],df.columns ])
但是编译return报错
NotImplementedError: isna is not defined for MultiIndex
我可以知道如何解决这个问题吗?
重现上述错误的代码
import pandas as pd
df = pd.DataFrame({'A': [11, 21, 31],
'B': [12, 22, 32],
'C': [13, 23, 33]},
index=['ONE', 'TWO', 'THREE'])
df.columns = pd.MultiIndex.from_product([['level1'],['level2'],df.columns ])
df.columns = pd.MultiIndex.from_product([['Top'],df.columns ])
预期输出
Top
level1
level2
A B C
ONE 11 12 13
TWO 21 22 23
THREE 31 32 33
使用pd.concat
:
>>> pd.concat([df], keys=['Top'], axis='columns')
Top
level1
level2
A B C
ONE 11 12 13
TWO 21 22 23
THREE 31 32 33
您还可以使用带有 concat 的字典:
pd.concat({'Top': df}, axis=1)
objective 是在 Pandas 中现有的多索引列之上添加另一个多索引。
我的印象是这可以实现如下
# Assuming we have an existing multilevel index as below
df.columns = pd.MultiIndex.from_product([['level1'],['level2'],df.columns ])
# Along the pipeline, we would like to append another multiindex on top of it
df.columns = pd.MultiIndex.from_product([['Top'],df.columns ])
但是编译return报错
NotImplementedError: isna is not defined for MultiIndex
我可以知道如何解决这个问题吗?
重现上述错误的代码
import pandas as pd
df = pd.DataFrame({'A': [11, 21, 31],
'B': [12, 22, 32],
'C': [13, 23, 33]},
index=['ONE', 'TWO', 'THREE'])
df.columns = pd.MultiIndex.from_product([['level1'],['level2'],df.columns ])
df.columns = pd.MultiIndex.from_product([['Top'],df.columns ])
预期输出
Top
level1
level2
A B C
ONE 11 12 13
TWO 21 22 23
THREE 31 32 33
使用pd.concat
:
>>> pd.concat([df], keys=['Top'], axis='columns')
Top
level1
level2
A B C
ONE 11 12 13
TWO 21 22 23
THREE 31 32 33
您还可以使用带有 concat 的字典:
pd.concat({'Top': df}, axis=1)