如何在Python中构造循环中的条件?
我想通过遍历给定的dictionarydict为函数中的数据帧构造一个条件如何在Python中构造循环中的条件?,python,pandas,conditional-statements,Python,Pandas,Conditional Statements,我想通过遍历给定的dictionarydict为函数中的数据帧构造一个条件 def get_condition(dataframe, dict={'col1':val1, 'col2':val2, 'col3':val3})": condition = ... return condition 预期产出 条件=(数据帧['col1']==val1)&(数据帧['col2']==val2)&(数据帧['col3']==val3) 如何做到这一点 如
def get_condition(dataframe, dict={'col1':val1, 'col2':val2, 'col3':val3})":
condition = ...
return condition
预期产出
条件=(数据帧['col1']==val1)&(数据帧['col2']==val2)&(数据帧['col3']==val3)
如何做到这一点 如果要创建布尔过滤器,则不确定
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
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
如果要创建布尔过滤器,则不确定
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
您想要构建一个字符串,还是实际执行并解决这个条件?最后我想要一个dataframe_new=dataframe[condition]。但是我想先用一个函数迭代地构造这个条件,如果我明白你的意思,我想先对字符串进行排序,然后再使用eval()就行了?但听起来像是密码的味道?请看答案。在参考原始代码时,请注意。另外,通过使用
dict
作为字典的变量名,您正在覆盖内置的dict类型/函数,如果可能的话,通常应该避免使用内置的dict类型/函数。您希望生成字符串,还是实际执行并解决此条件?最后,我希望有一个dataframe\u new=dataframe[condition]。但是我想先用一个函数迭代地构造这个条件,如果我明白你的意思,我想先对字符串进行排序,然后再使用eval()就行了?但听起来像是密码的味道?请看答案。在参考原始代码时,请注意。另外,通过使用dict
作为字典的变量名,您正在覆盖内置的dict类型/函数,如果可能的话,通常应该避免使用内置的dict类型/函数。