所以我試圖將一個變量操作(用戶定義的)傳遞給一個函數,並且在試圖找到一個好的方法時遇到了困難。所有我能想到的做的是硬編碼的所有選項進入的功能等以下幾點:Python在字符串中執行操作
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
這是一切都很好,一切,但我不知道是否有一種更好或更有效的方式將條件傳遞給函數,而不用寫出所有可能的語句。有任何想法嗎?
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
這正是我一直在尋找的。謝謝。回答有問題。 – 2013-05-13 22:54:53
雖然這回答了OP(或任何其他人在這裏絆倒)如何做到這一點......他們真的不應該推出他們自己的(效率較低)numpy屏蔽。 – 2013-05-14 01:53:33
@AndyHayden:「任何人在這裏都有絆腳石」可能不會使用numpy--他們可能只是尋找一種簡潔的方式來實現一組運算符。苛刻downvote恕我直言。 – RichieHindle 2013-05-14 07:02:58