使用索引中的模式将索引 DataFrame 转换为多索引
Convert indexed DataFrame to multi-indexed using pattern in indices
我有具有以下结构的 DataFrame(即索引有一些词法交集):
a b
bar foo bah foo
A1B1 1 0 3 2
A1B2 5 4 7 6
A2B1 9 8 11 10
A2B2 13 12 15 14
我希望将这个 DataFrame 转换成这个(即使用一些正则表达式从索引中提取多索引):
a b
bar foo bah foo
A1 B1 1 0 3 2
B2 5 4 7 6
A2 B1 9 8 11 10
B2 13 12 15 14
我可能只使用地图:
In [11]: df.index = pd.MultiIndex.from_tuples(df.index.map(lambda x: (x[0:2], x[2:4])))
In [12]: df
Out[12]:
a b
bar foo bah foo
A1 B1 1 0 3 2
B2 5 4 7 6
A2 B1 9 8 11 10
B2 13 12 15 14
您可以使用正则表达式或其他任何方式,前提是您传递给 map 的函数接受每个项目和 returns 一个元组。
我有具有以下结构的 DataFrame(即索引有一些词法交集):
a b
bar foo bah foo
A1B1 1 0 3 2
A1B2 5 4 7 6
A2B1 9 8 11 10
A2B2 13 12 15 14
我希望将这个 DataFrame 转换成这个(即使用一些正则表达式从索引中提取多索引):
a b
bar foo bah foo
A1 B1 1 0 3 2
B2 5 4 7 6
A2 B1 9 8 11 10
B2 13 12 15 14
我可能只使用地图:
In [11]: df.index = pd.MultiIndex.from_tuples(df.index.map(lambda x: (x[0:2], x[2:4])))
In [12]: df
Out[12]:
a b
bar foo bah foo
A1 B1 1 0 3 2
B2 5 4 7 6
A2 B1 9 8 11 10
B2 13 12 15 14
您可以使用正则表达式或其他任何方式,前提是您传递给 map 的函数接受每个项目和 returns 一个元组。