2024-04-23 00:16:18 发布
网友
如果我有多级列索引:
>>> cols = pd.MultiIndex.from_tuples([("a", "b"), ("a", "c")]) >>> pd.DataFrame([[1,2], [3,4]], columns=cols)
a ---+-- b | c --+---+-- 0 | 1 | 2 1 | 3 | 4
我怎样才能降低该索引的“a”级别,所以我最终得到:
b | c --+---+-- 0 | 1 | 2 1 | 3 | 4
另一种方法是使用.xs方法,基于df的横截面重新分配df。
df
>>> df a b c 0 1 2 1 3 4 >>> df = df.xs('a', axis=1, drop_level=True) # 'a' : key on which to get cross section # axis=1 : get cross section of column # drop_level=True : returns cross section without the multilevel index >>> df b c 0 1 2 1 3 4
另一种删除索引的方法是使用列表理解:
df.columns = [col[1] for col in df.columns] b c 0 1 2 1 3 4
如果要将两个级别的名称组合在一起,则此策略也很有用,如下面的示例中,其中底部级别包含两个“y”:
cols = pd.MultiIndex.from_tuples([("A", "x"), ("A", "y"), ("B", "y")]) df = pd.DataFrame([[1,2, 8 ], [3,4, 9]], columns=cols) A B x y y 0 1 2 8 1 3 4 9
删除顶层将留下两列索引为“y”。这可以通过将名字与列表理解结合起来来避免。
df.columns = ['_'.join(col) for col in df.columns] A_x A_y B_y 0 1 2 8 1 3 4 9
这是我在做了一个groupby后遇到的问题,花了一段时间才找到解决问题的this other question。我根据这里的具体情况修改了这个解决方案。
您可以使用^{}:
>>> cols = pd.MultiIndex.from_tuples([("a", "b"), ("a", "c")]) >>> df = pd.DataFrame([[1,2], [3,4]], columns=cols) >>> df a b c 0 1 2 1 3 4 [2 rows x 2 columns] >>> df.columns = df.columns.droplevel() >>> df b c 0 1 2 1 3 4 [2 rows x 2 columns]
另一种方法是使用.xs方法,基于
df
的横截面重新分配df
。另一种删除索引的方法是使用列表理解:
如果要将两个级别的名称组合在一起,则此策略也很有用,如下面的示例中,其中底部级别包含两个“y”:
删除顶层将留下两列索引为“y”。这可以通过将名字与列表理解结合起来来避免。
这是我在做了一个groupby后遇到的问题,花了一段时间才找到解决问题的this other question。我根据这里的具体情况修改了这个解决方案。
您可以使用^{} :
相关问题 更多 >
编程相关推荐