2016-08-04 73 views
1
df1 = pd.DataFrame({'A' : [5,5,5,5], 'B' : [4,2,1, 1], 'C' : [2,2,7,1]}) 

我想根据foll获取df1中的那些行。条件:编写python函数以从熊猫数据框中提取匹配行

df1.loc[(df1['A'] == 5) & (df1['B'] == 4) & (df1['C'] == 2)] 

我怎样才能使它更通用,即我想有一个函数,在那里我指定列名和我正在寻找的值作为参数。

回答

3

一选项将使用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 
+0

谢谢@root,如果您的解决方案不是数字,而是字符串比较,您的解决方案是否工作? – user308827

+1

是的,但不是很直接。查询字符串需要在其中引用:“'== ==”是“&B == 4''。为了得到这个,你需要在你的字符串中引用引号,例如在引用你的字符串的单引号内的双引号,反之亦然:'('A','==',''yes''')'。 – root

+1

或者,你可以在你的函数中实现一个检查来确定你是否与一个字符串进行比较,如果是这样,那么格式化你的查询的方式略有不同:''{} {}“{}”'。format(* c)' 。 – root

1

你需要这样的事情,filterdf是你的函数:

import pandas as pd 

df1 = pd.DataFrame({'A' : [5,5,5,5], 'B' : [4,2,1,1], 'C' : [2,2,7,1]}) 

def filterdf(df,col1,col2,val1,val2): 
    return df[(df[col1] == val1) & (df[col2] == val2)] 

df2 = filterdf(df1,'A','B',5,4) 
print(df2) 
Out: 
    A B C 
0 5 4 2 
+0

请让我知道了什么是问题downvoting之前! –

+0

@GuaravDhama我看不到问题。在我看来,反对票是不合理的。从我+1。 – piRSquared

2

指定你正在寻找的一系列什么

# first row of df1 
looking_for = df1.iloc[0, :] 

然后评估平等并找到所有的都在一个平等的行。

df1.eq(looking_for).all(1) 

0  True 
1 False 
2 False 
3 False 
dtype: bool 

使用此作为过滤器

df1[df1.eq(looking_for).all(1)] 

enter image description here

一般地,指定任意系列

looking_for = pd.Series([1, 5, 7], list('BAC')) 

df1[df1.eq(looking_for).all(1)] 

enter image description here