Python 按索引选择和按布尔掩码过滤

Python 按索引选择和按布尔掩码过滤,python,pandas,filtering,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] 我希望能够使用布尔掩码过滤和索引(我在其他地方定义)对此进行选择,例如 如何将它们结合使用?我要选择的内容(从索引2,4) 我试过了,但熊猫不知道如何将索引和布尔掩码一起使用 test[test.loc[in

我有以下数据帧

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]
我希望能够使用布尔掩码过滤和索引(我在其他地方定义)对此进行选择,例如

如何将它们结合使用?我要选择的内容(从索引2,4)

我试过了,但熊猫不知道如何将索引和布尔掩码一起使用

test[test.loc[ind,:] & test['a'] == 1] # Don't work
您可以这样做:

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

    1 blah    a
2  34    c  1.0
您可以使用:

还有一种方法:

test.loc[ind & test.index.where(test['a'] == 1)]
    1 blah    a
2  34    c  1.0
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
test.loc[ind & test.index.where(test['a'] == 1)]