3 回答
TA贡献2065条经验 获得超14个赞
我们只用了isin两次
df1=df.loc[df.D_val.isin(list2)&df.P_val.isin(list1)]
df1
Out[211]:
D_val P_val D_PCode
0 A 1 25
2 C 2 32
5 B 1 3
6 C 1 312
TA贡献1815条经验 获得超13个赞
您可以使用itertools.product生成所有可能的值,然后使用isin:
from itertools import product
import pandas as pd
data = [['A', 1, 25],
['D', 1, 21],
['C', 2, 32],
['B', 4, 35],
['D', 2, 126],
['B', 1, 3],
['C', 1, 312]]
df = pd.DataFrame(data=data, columns=['D_val', 'P_val', 'D_PCode'])
list1 = [1, 2]
list2 = ['A', 'B', 'C']
lookup = set(product(list2, list1))
mask = df[['D_val', 'P_val']].apply(tuple, axis=1).isin(lookup)
result = df[mask].D_PCode
print(result)
输出
0 25
2 32
5 3
6 312
Name: D_PCode, dtype: int64
或者直接在两列上使用 isin,例如:
list1 = [1, 2]
list2 = ['A', 'B', 'C']
result = df[df.D_val.isin(list2) & df.P_val.isin(list1)].D_PCode
print(result)
输出
0 25
2 32
5 3
6 312
Name: D_PCode, dtype: int64
添加回答
举报