英文:
Select 2 different set of columns from column multiindex dataframe
问题
我有以下的列多级索引数据框。
我想选择(或获取)每个level_0索引的不同列的数据框子集(即virtual中的x_mm和y_mm以及actual中的z_mm、rx_deg、ry_deg和rz_deg)。从我所了解的情况来看,我认为可以使用pandas的IndexSlice,但不太确定如何在这种情况下使用它。
到目前为止,我的解决方法是使用pd.concat
分别选择两组列。我有一种感觉这可以通过切片方法更整洁地完成。
英文:
I have the following column multiindex dataframe.
I would like to select (or get a subset) of the dataframe with different columns of each level_0 index (i.e. x_mm and y_mm from virtual and z_mm rx_deg ry_deg rz_deg from actual). From what I have read I think I might be able to use pandas IndexSlice but not entire sure how to use it in this context.
So far my work around is to use pd.concat
selecting the 2 sets of columns independently. I have the feeling that this can be done neatly with slicing.
答案1
得分: 1
你可以通过编程生成元组来切片你的 MultiIndex:
from itertools import product
cols = ((('virtual',), ('x_mm', 'y_mm')),
(('actual',), ('z_mm', 'rx_deg', 'ry_deg', 'rz_deg'))
)
out = df[[t for x in cols for t in product(*x)]]
英文:
You can programmatically generate the tuples to slice your MultiIndex:
from itertools import product
cols = ((('virtual',), ('x_mm', 'y_mm')),
(('actual',), ('z_mm', 'rx_deg', 'ry_deg', 'rz_deg'))
)
out = df[[t for x in cols for t in product(*x)]]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论