[英]How to construct condition in a loop in Python?
I want to construct a condition for my dataframe in a function by iterating through the given dictionary dict . 我想通过遍历给定的字典dict为函数中的数据帧构造条件。
def get_condition(dataframe, dict={'col1':val1, 'col2':val2, 'col3':val3})":
condition = ...
return condition
Expected output 预期产量
condition = (dataframe['col1']==val1) & (dataframe['col2']==val2) & (dataframe['col3']==val3)
How to do this? 这个怎么做?
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
Not sure, if you want to create a boolean filter. 不确定,是否要创建布尔过滤器。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.