1

所以我试图将一个变量操作(用户定义)传递给一个函数,并且在试图找到一个好的方法时遇到了麻烦。我能想到的就是将所有选项硬编码到函数中,如下所示:

def DoThings(Conditions):
import re
import pandas as pd
d = {'time' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd']),
     'legnth' : pd.Series([4., 5., 6., 7.], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(d)
print df

for Condition in Conditions:
    # Split the condition into two parts
    SplitCondition = re.split('<=|>=|!=|<|>|=',Condition)

    # If the right side of the conditional statement is a number convert it to a float
    if SplitCondition[1].isdigit():
        SplitCondition[1] = float(SplitCondition[1])

    # Perform the condition specified
    if "<=" in Condition:
        df = df[df[SplitCondition[0]]<=SplitCondition[1]]
        print "one"
    elif ">=" in Condition:
        df = df[df[SplitCondition[0]]>=SplitCondition[1]]
        print "two"
    elif "!=" in Condition:
        df = df[df[SplitCondition[0]]!=SplitCondition[1]]
        print "three"
    elif "<" in Condition:
        df = df[df[SplitCondition[0]]<=SplitCondition[1]]
        print "four"
    elif ">" in Condition:
        df = df[df[SplitCondition[0]]>=SplitCondition[1]]
        print "five"
    elif "=" in Condition:
        df = df[df[SplitCondition[0]]==SplitCondition[1]]
        print "six"
return df

# Specify the conditions
Conditions = ["time>2","legnth<=6"]
df = DoThings(Conditions)   # Call the function

print df

结果是:

   legnth  time
a       4     1
b       5     2
c       6     3
d       7     4
five
one
   legnth  time
c       6     3

这一切都很好,一切都很好,但我想知道是否有更好或更有效的方法将条件传递给函数,而无需编写所有可能的 if 语句。有任何想法吗?

解决方案:

def DoThings(Conditions):
    import re
    import pandas as pd
    d = {'time' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd']),
         'legnth' : pd.Series([4., 5., 6., 7.], index=['a', 'b', 'c', 'd'])}
    df = pd.DataFrame(d)
    print df

    for Condition in Conditions:
        # Split the condition into two parts
        SplitCondition = re.split('<=|>=|!=|<|>|=',Condition)

        # If the right side of the conditional statement is a number convert it to a float
        if SplitCondition[1].isdigit():
            SplitCondition[1] = float(SplitCondition[1])

        import operator
        ops = {'<=': operator.le, '>=': operator.ge, '!=': operator.ne, '<': operator.lt, '>': operator.gt, '=': operator.eq}
        cond = re.findall(r'<=|>=|!=|<|>|=', Condition)
        df = df[ops[cond[0]](df[SplitCondition[0]],SplitCondition[1])]

    return df



# Specify the conditions
Conditions = ["time>2","legnth<=6"]
df = DoThings(Conditions)   # Call the function

print df

输出:

   legnth  time
a       4     1
b       5     2
c       6     3
d       7     4
   legnth  time
c       6     3
4

3 回答 3

4

您可以通过模块访问内置运算符operator,然后构建一个表,将您的运算符名称映射到内置运算符,如以下简化示例中所示:

import operator
ops = {'<=': operator.le, '>=': operator.ge}

In [3]: ops['>='](2, 1)
Out[3]: True
于 2013-05-13T17:15:50.033 回答
2

你可以使用遮罩来做这种操作(你会发现它快很多):

In [21]: df[(df.legnth <= 6) & (df.time > 2)]
Out[21]:
   legnth  time
c       6     3

In [22]: df[(df.legnth <= 6) & (df.time >= 2)]
Out[22]:
   legnth  time
b       5     2
c       6     3

注意:您的实现中有一个错误,因为 b 不应该包含在您的查询中。

您还可以执行或(使用|)操作,这些操作可以按您的预期工作:

In [23]: df[(df.legnth == 4) | (df.time == 4)]
Out[23]:
   legnth  time
a       4     1
d       7     4
于 2013-05-13T17:33:20.097 回答
0

pandas==0.13(不确定何时发布......0.12刚刚发布)您将能够执行以下操作,所有这些都是等效的:

res = df.query('(legnth == 4) | (time == 4)')
res = df.query('legnth == 4 | time == 4')
res = df.query('legnth == 4 or time == 4')

和我个人的最爱

res = df['legnth == 4 or time == 4']

query并且__getitem__两者都接受任意布尔表达式并自动在表达式中的每个变量名称上为调用框架实例“添加前缀”(您也可以使用局部变量和全局变量)。这使您可以 1) 比在所有内容前面键入更简洁地df.表达查询 2) 使用语法表达查询,让我们面对它,看起来比丑陋的按位运算符更好,3) 可能比“纯” Python 等价物快得多如果你有巨大的框架和一个非常复杂的表达式,最后 4) 允许你将相同的查询传递给多个框架(毕竟,它是一个字符串),其中有一个共同的列子集。

于 2013-07-29T02:28:34.527 回答