根据列值删除多级索引Pandas中的DataFrame行

rsc05

考虑下面的多级DataFrame

import numpy as np
import pandas as pd
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
   ...:           ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
s = pd.DataFrame(np.random.randn(8, 4), index=arrays)
s

可以说我想删除整个带有index_0 bar和index_1两个的行

我该怎么办?

忘了它

您可以使用以下drop方法

In [26]: s.drop(('bar','two'), axis=0)
Out[26]: 
                0         1         2         3
bar one -0.450943 -1.615345 -0.862521  1.042495
baz one  1.200944  0.617102 -0.439342 -0.296142
    two -0.879343 -1.055805  0.682381  2.625398
foo one  0.191370 -0.212905 -0.415360 -1.437934
    two  0.458979  1.072584  0.485136  1.498859
qux one -2.137894 -0.872023 -0.382530 -0.550116
    two -1.490523 -2.999998  0.290653 -0.848422

axis=0是没有必要的(这是缺省的),但我包括它只是要明确的是,我们都在不断下降行,不列。


如果您想删除多个行(例如('bar','two')和和('baz','one')行),则可以使用isin生成布尔掩码:

In [55]: s.index.isin((('bar','two'),('baz','one')))
Out[55]: array([False,  True,  True, False, False, False, False, False], dtype=bool)

然后用于s.loc选择行:

In [56]: s.loc[~s.index.isin((('bar','two'),('baz','one')))]
Out[56]: 
                0         1         2         3
bar one -0.450943 -1.615345 -0.862521  1.042495
baz two -0.879343 -1.055805  0.682381  2.625398
foo one  0.191370 -0.212905 -0.415360 -1.437934
    two  0.458979  1.072584  0.485136  1.498859
qux one -2.137894 -0.872023 -0.382530 -0.550116
    two -1.490523 -2.999998  0.290653 -0.848422

~反转的面具,让我们保持行,其中布尔掩码为假。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章