Python 在字符串中执行操作

标签 python pandas conditional-statements

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

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

最佳答案

您可以通过 operator 模块访问内置运算符,然后构建一个将您的运算符名称映射到内置运算符的表,就像这个缩减示例一样:

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

In [3]: ops['>='](2, 1)
Out[3]: True

关于Python 在字符串中执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16527491/

相关文章:

java - 将 dict 的 dict 转换为 json

python - seaborn.pairplot() 改变每个图形的颜色

python - 如何从 pandas DataFrame 中删除列?

python - 如何在pandas数据框中的 `convert_objects`中产生异常

比较两个数组并检查条件

python - 根据数值有条件创建数据框列

java - 如何检查 for 循环中的条件并打印一次语句?

python - 如何从python中的文件(json或yaml)动态创建参数化测试

python - selenium twitter 登录没有新设备通知

python - Pandas Dataframe.to_csv - 将变量值插入到 csv 文件的开头