Skip to content
Advertisement

Most efficient way of applying a function based on condition

Suppose we have a master dictionary master_dict = {"a": df1, "b": df2, "c": df3}. Now suppose we have a list called 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.

What is the best way to get the below code to work when the length of condition_list is greater than 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]]

Advertisement

Answer

You need to ask clearly. Declare input and output. And try to make a demo code. 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. Search “select dataframe with multiple conditions”

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement