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