Skip to main content
 首页 » 编程设计

python之Pandas 如何切片多索引数据帧

2025年05月04日14txw1958

           name                     address             contact_info     
        first_name  last_name       stret   city    mobile      email 
    1   AAA             BBB         XXX     YYY     02020       aaa@xyz.com 
    2   111             222         333     444     239393      bbb@xyz.com 

我有一个上述格式的excel。我想要的是让每一列都在 name 中,然后只有 mobile 列在 contact_info 中,有人请告诉我如何做到这一点。以下代码为我提供了 name 和 contact_info

中的所有内容
import pandas as pd 
df = pd.read_excel("test.xlsx", header=[0, 1], sheet_name="Mapping") 
print df[["name", "contact_info"]] 

我想得到这样的东西,

first_name  last_name   mobile 
AAA         BBB        102020 
111         222        239393 

请您参考如下方法:

通过使用IndexSlice + concat

idx = pd.IndexSlice 
pd.concat([df.loc[:, idx['name',:]],df.loc[:,idx[:,'mobile']]]) 
Out[104]:  
   contact_info       name           
         mobile first_name last_name 
1           NaN        AAA       BBB 
2           NaN        111       222 
1          2020        NaN       NaN 
2        239393        NaN       NaN