1

I have a function to perform multiple tasks. And I need to pass optional strings/variables and optional data frame with other values. For example, this is my function.

def main(df,option=None,type=None, *args)
    if type == "cars":
       #multiple functions..
       df      = function1(df)
       results = function2(df)
       if option =="ex":
          results = function4(results)
       elif option =="CDS":
           result  = function5(results)
    elif type == "buses":
         df2 = pd_read_csv("data2",sep="\t",header=0) # This is the optional data frame I wannna pass
         def func3(df2,results,df):
             result["col3"] =pd.merge(df2,df, on="col1")
             return result
         if option =="ex":
            results = function4(results)
         elif option =="CDS":
            result  = function5(results)
     return(result)

I have two optional variables passed to my function main already option and type. Now I need to pass one more optional variable that is df2. But I do not know how can do it. The above example is a template from my main function. Here, I wanna add df2 to the main() and use it in first elif loop for buses.

Any suggestions or help is much appreciated

2
  • def main(df,option=None,type=None,df2=None, *args)? Commented Sep 26, 2019 at 11:07
  • But how to call it later? I mean as a data frame. This is not a string and I want to call it in the elif loop. Commented Sep 26, 2019 at 11:09

2 Answers 2

3

You can use *args argument in main function to pass the optional parameters such as df2, as:

def main(df,option=None,type=None, *args):
    df2=args[0]    # here you will get the df2

# call main function as
main(df,option,type,df2)

OR

You can also use kwargs to pass keyword optional arguments as,

def main(df,option=None,type=None, **kwargs):
    df2=kwargs['df2']   # here you will get the df2

# call main function as
main(df,option,type,df2=df2)

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

1

Looks like you need.

def main(df,option=None,type=None,df2=None, *args):
    if df2 is not None:
        #Process df2 ....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.