熊猫按索引选择并按布尔掩码过滤

时间:2019-07-30 04:52:39

标签: python pandas filtering

我有以下数据框

import pandas as pd

test = pd.DataFrame()
test['1'] = [12,23,34, 45]
test['blah'] = ['a', 'b', 'c', 'e']
test['a'] = [None, 1, 1, None]

我希望能够同时使用布尔掩码过滤和索引(我在其他地方定义)进行选择,例如

test['a'] == 1  # filter

ind = pd.RangeIndex(start=0, stop=4, step=2)  # pd index object

如何一起使用它们?我要选择的内容(从索引2,4开始)

index   1       blah  a
2       34      c     1.0

我尝试过,但是熊猫不懂如何同时使用索引和布尔型掩码

test[test.loc[ind,:] & test['a'] == 1] # Don't work

3 个答案:

答案 0 :(得分:2)

您可以使用numpy.intersect1d

arr = np.intersect1d(test.index[test['a'].eq(1)], ind)
#alternative arr = set(test.index[test['a'].eq(1)]).intersection(ind) 

print(test.loc[arr, :])
    1 blah    a
2  34    c  1.0

答案 1 :(得分:0)

您可以这样做:

test.loc[(test.index.isin(ind)) & (test['a'] == 1)]

输出:

    1 blah    a
2  34    c  1.0

答案 2 :(得分:0)

这是另一种方式:

test.loc[ind & test.index.where(test['a'] == 1)]