使用字典过滤DataFrame

4

我是pandas和python的新手。 我想使用字典来过滤DataFrame。

import pandas as pd
from pandas import DataFrame

df = DataFrame({'A': [1, 2, 3, 3, 3, 3], 'B': ['a', 'b', 'f', 'c', 'e', 'c'], 'D':[0,0,0,0,0,0]})
my_filter = {'A':[3], 'B':['c']}

当我调用时

df[df.isin(my_filter)]

我明白了

     A    B   D
0  NaN  NaN NaN
1  NaN  NaN NaN
2  3.0  NaN NaN
3  3.0    c NaN
4  3.0  NaN NaN
5  3.0    c NaN

What I want is

     A    B   D
3  3.0    c   0
5  3.0    c   0

我不想在字典中添加“D”,我想获取在A和B列中具有适当值的行。

1个回答

6
您可以按列求和sumTrue,然后与2进行比较。
print (df.isin(my_filter).sum(1) == 2)
0    False
1    False
2    False
3     True
4    False
5     True
dtype: bool

print (df[df.isin(my_filter).sum(1) == 2])
   A  B  D
3  3  c  0
5  3  c  0

另一种解决方案是只使用第一个过滤器,仅筛选具有条件 AB 的列,并使用 all 来检查所有列是否都为 True

print (df[df[['A','B']].isin(my_filter).all(1)])
   A  B  D
3  3  c  0
5  3  c  0

感谢 MaxU 提供更灵活的解决方案:

print (df[df.isin(my_filter).sum(1) == len(my_filter.keys())])
   A  B  D
3  3  c  0
5  3  c  0

是的,它的意思是计算字典键的长度 - 在这个示例中,它是2,因为键是 dict_keys(['A', 'B']) - jezrael

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接