如何在Python的循环中构造条件?

时间:2018-07-26 13:35:31

标签: python pandas conditional-statements

我想通过遍历给定的字典 dict 为函数中的数据框构造条件。

def get_condition(dataframe, dict={'col1':val1, 'col2':val2, 'col3':val3})":

     condition = ...          

     return condition  

预期产量

condition = (dataframe['col1']==val1) & (dataframe['col2']==val2) & (dataframe['col3']==val3)

如何执行此操作?

2 个答案:

答案 0 :(得分:1)

def get_condition(df, d):
    d = list(d.items())

    first_col, first_val = d[0]
    cond = df[first_col] == first_val
    for col, val in d[1:]:
        cond &= df[col] == val

    return cond

答案 1 :(得分:1)

不确定,是否要创建布尔过滤器。

def get_condition(dataframe, dictionary):
    # create series with all values set to true
    condition = pd.Series([True] * len(dataframe))

    for k, v in dictionary.items():
        condition &= dataframe[k] == v
    return condition