简体   繁体   English

使用多个索引从Pandas数据框中删除列

[英]Delete columns from Pandas dataframe with multiple indexes

I have a PANDAS dataframe with a two line index. 我有一个带有两行索引的PANDAS数据帧。 I want to keep certain columns based on the second line index. 我想根据第二行索引保留某些列。 How could I do it? 我怎么能这样做? I have tried a few things but nothing worked. 我尝试过一些东西,但没有任何效果。 For example, consider the following dataframe: 例如,请考虑以下数据帧:

         AAA              BBB              CCC
         C1   C2   C3     C1   C2   C3     C1   C2   C3
Index   
1        1    2    3      4    5    6      1    2    3
2        2    5    0      7    8    9      7    4    5
3        7    4    1      5    7    2      2    5    9

How can I keep only column C2 for all cases (ie for AAA, BBB, CCC). 如何为所有情况(即AAA,BBB,CCC)仅保留C2列。 As a result I would like to have: 结果我希望:

             AAA BBB CCC
             C2  C2  C2
   Index
   1         2   5   2
   2         5   8   4
   3         4   7   5

Thanks in advance for the help. 先谢谢您的帮助。

Let me just give you an example: 我来举个例子:

df = pd.DataFrame(np.random.randint(9,size=(3,9)))
df.columns = pd.MultiIndex.from_product([['AAA','BBB','CCC'],['C1','C2','C3']])

      AAA       BBB       CCC      
   C1 C2 C3  C1 C2 C3  C1 C2 C3
0   8  3  7   2  8  7   1  8  2
1   8  3  1   8  5  2   0  1  0
2   4  0  0   5  8  4   7  1  5

df.iloc[:, df.columns.get_level_values(1)=='C2'] # note get_level_values()

  AAA BBB CCC
   C2  C2  C2
0   3   8   8
1   3   5   1
2   0   8   1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM