简体   繁体   English

在熊猫数据框中删除特定的multiIndex列

[英]Drop specific multiIndex columns in a pandas dataframe

Suppose one has a dataframe created as such: 假设一个具有这样创建的数据框:

tdata = {('A', 50): [1, 2, 3, 4],
         ('A', 55): [5, 6, 7, 8],
         ('B', 10): [10, 20, 30, 40],
         ('B', 20): [50, 60, 70, 80],
         ('B', 50): [2, 4, 6, 8],
         ('B', 55): [10, 12, 14, 16]}
tdf = pd.DataFrame(tdata, index=range(0,4))

      A      B
     50 55  10  20 50  55
   0  1  5  10  50  2  10
   1  2  6  20  60  4  12
   2  3  7  30  70  6  14
   3  4  8  40  80  8  16
  1. How would one drop specific columns, say ('B', 10) and ('B', 20) from the dataframe? 如何从数据框中删除特定的列,例如('B',10)和('B',20)?
  2. Is there a way to drop the columns in one command such as tdf.drop(['B', [10,20]]) ? 有没有办法在一个命令(例如tdf.drop(['B', [10,20]])删除列? Note, I know that my example of the command is by no means close to what it should be, but I hope that it gets the gist across. 请注意,我知道我的命令示例与它应有的示例绝不相近,但我希望它能使您理解要点。
  3. Is there a way to drop the columns through some logical expression? 有没有办法通过一些逻辑表达式删除列? For example, say I want to drop columns having the sublevel indices less than 50 (again, the 10, 20 columns). 例如,假设我要删除子级索引小于50的列(再次是10、20列)。 Can I do some general command that would encompass column 'A', even though the 10,20 sublevel indices don't exist or must I specifically reference column 'B'? 即使10,20个子级索引不存在,我是否也可以执行一些包含“ A”列的常规命令,还是必须专门引用“ B”列?

You can use drop by list of tuples : 您可以使用drop通过listtuples

print (tdf.drop([('B',10), ('B',20)], axis=1))
   A     B    
  50 55 50  55
0  1  5  2  10
1  2  6  4  12
2  3  7  6  14
3  4  8  8  16

For remove columns by level : 对于按level删除列:

mask = tdf.columns.get_level_values(1) >= 50
print (mask)
[ True  True False False  True  True]

print (tdf.loc[:, mask])
   A     B    
  50 55 50  55
0  1  5  2  10
1  2  6  4  12
2  3  7  6  14
3  4  8  8  16

If need remove by level is possible specify only one level: 如果需要按级别删除,则仅指定一个级别:

print (tdf.drop([50,55], axis=1, level=1))
    B    
   10  20
0  10  50
1  20  60
2  30  70
3  40  80

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

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