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

时间:2017-02-04 12:44:43

标签: python-3.x pandas dataframe

考虑以下Multilevel 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两个

删除整行

我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

您可以使用drop method

@classmethod
def state_from_request(cls, request):
    if next_url:
        state['next'] = next_url
    return state

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 反转掩码,以便我们保留布尔掩码为False的行。