所以我试图将一个变量操作(用户定义)传递给一个函数,并且在尝试找到一个好方法时遇到了麻烦。我能想到的就是将所有选项硬编码到函数中,如下所示:
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语句。有什么想法吗?
SOLUTION:
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
答案 0 :(得分:4)
您可以通过operator
模块访问内置运算符,然后构建一个将运算符名称映射到内置运算符的表,如下面的示例所示:
import operator
ops = {'<=': operator.le, '>=': operator.ge}
In [3]: ops['>='](2, 1)
Out[3]: True
答案 1 :(得分:2)
您可以使用masking执行此类操作(您会发现 lot 更快):
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
答案 2 :(得分: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__
都接受一个任意的布尔表达式,并在表达式中的每个变量名称上自动“加上”调用帧实例(你也可以使用locals和globals)。这允许你1)比在所有内容中输入df.
更简洁地表达查询2)使用语法表达查询,让我们面对它,看起来比丑陋的按位运算符更好,3)可能比如果你有庞大的框架和非常复杂的表达式,那么“纯粹的”Python等效,最后4)允许你将相同的查询传递给多个框架(毕竟,它是一个字符串),并且有一个共同的列子集。