[英]Most efficient way of applying a function based on condition
Suppose we have a master dictionary master_dict = {"a": df1, "b": df2, "c": df3}
.假设我们有一个主字典master_dict = {"a": df1, "b": df2, "c": df3}
。 Now suppose we have a list called condition_list
.现在假设我们有一个名为condition_list
的列表。 Suppose func
is a function that returns a new dictionary that has the original keys of master_dict
along with potentially new keys.假设func
是一个 function,它返回一个新字典,该字典具有master_dict
的原始键以及潜在的新键。
What is the best way to get the below code to work when the length of condition_list
is greater than 2:当condition_list
的长度大于 2 时,让下面的代码工作的最佳方法是什么:
if(len(condition_list) == 1):
df = master_dict[condition_list[0]]
else:
df = func(master_dict(condition_list[0]))
df = df[condition_list[1]]
You need to ask clearly.你要问清楚。 Declare input and output. And try to make a demo code.声明输入和output。并尝试制作一个演示代码。 Anyway, use a loop.无论如何,使用循环。
for i in range(len(condition_list)):
if i==0: df = master_dict[condition_list[i]]
else: df = func(df)[condition_list[i]];
If the "df" is a dataframe of pandas, the conditions can be applied at once.如果“df”是 pandas 的 dataframe,则可以立即应用条件。 Search "select dataframe with multiple conditions"搜索“多条件选择dataframe”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.