df1 = pd.DataFrame({'A' : [5,5,5,5], 'B' : [4,2,1, 1], 'C' : [2,2,7,1]})
我想根据 foll 在 df1 中获取这些行。条件:
df1.loc[(df1['A'] == 5) & (df1['B'] == 4) & (df1['C'] == 2)]
我怎样才能让它更通用,即我想要一个函数,我在其中指定列名和我要查找的值作为参数。
请您参考如下方法:
一个选择是使用 query .对于您问题中的条件,这将涉及沿 'A==5 & B==4 & C==2' 行构造一个字符串。
为了设置问题,我假设您以 (column, comparison, value) 的形式提供了一个元组列表作为您的条件,例如 (' A', '==', 5).
然后您可以按照以下行编写一个函数:
def extract_matching_rows(df, conditions):
conditions = ' & '.join(['{}{}{}'.format(*c) for c in conditions])
return df.query(conditions)
如果您只关心相等性比较,您可以在 '==' 中硬编码并将其从您的条件元组中删除。
条件稍有不同的用法示例:
conditions = [('A', '>=', 5), ('B', '==', 4), ('C', '<', 3)]
extract_matching_rows(df1, conditions)
A B C
0 5 4 2
请注意,您甚至可以使用 query 比较列:
conditions = [('B', '>=', 'C'), ('A', '==', 5)]
extract_matching_rows(df1, conditions)
A B C
0 5 4 2
1 5 2 2
3 5 1 1
