从列多级索引的数据框中选择两个不同的列集。

huangapple go评论56阅读模式
英文:

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)]]

huangapple
  • 本文由 发表于 2023年2月16日 03:59:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75464878.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定