【发布时间】:2021-08-31 12:01:11
【问题描述】:
【问题讨论】:
-
通过
tuple()例如df.loc[:,('Close','A')] -
你有多个索引列......所以黄色部分是level0,黑色部分是level1
标签: python pandas multi-index
【问题讨论】:
tuple() 例如df.loc[:,('Close','A')]
标签: python pandas multi-index
层级从0、1等开始命名,最上层为0
您可以通过pandas.MultiIndex.get_level_values 访问每个级别。例如,您可以使用以下内容来获取您想要的列索引的级别1(从顶部开始的第二级):
df.columns.get_level_values(1)
【讨论】:
你有多个索引列......所以黄色部分是level 0,黑色部分是level 1
所以如果你想访问值然后使用(例如):
df.loc[:,('Close','A')] #for selecting a single column
#OR
df.loc[:, df.columns.get_level_values(1)=='A'] #for selecting all values at level 1 where column is 'A'
#OR
df.loc[:, df.columns.get_level_values(0)=='Close'] #for selecting all values at level 0 where column is 'Close'
如果要创建单级索引,则必须删除 level 0 或 level 1
df=df.droplevel(0,1) #for removing the columns name in yellow part
#OR
df=df.droplevel(1,1) #for removing the columns name in black part
如果您不想失去任何级别,那么您可以将这 2 个级别合并为一个级别,以便您可以像往常一样访问列:
df.columns=df.columns.map('_'.join)
#here the both level is joined by '_' btw you can use any custum character for joining levels
更多信息请参考documentation
This article 也可能有帮助
【讨论】: