0

I want to define my own function as below:

def myown(df, ADD1, ADD2 = None, OtherArgument_1, OtherArgument_2):
    tmp = df
    tmp['NEWADD'] = (tmp['ADD1'] + ' ' + tmp['ADD2']).str.strip()
    return tmp 

I know this is incorrect so I can add if statement in the function.

def myown(df, ADD1, ADD2 = None, OtherArgument_1, OtherArgument_2):
    tmp = df
    if ADD2 == None:
        tmp['NEWADD'] = tmp[ADD1].str.strip()
    else:
        tmp['NEWADD'] = (tmp[ADD1] + ' ' + tmp[ADD2]).str.strip()

However, If I don know how many ADD inputs at first, how can I modify this?
For example, there are 5 ADD need to be combined this time and next time it may be 3. It is difficult to re-write function each time like this:

def myown(df, ADD1, ADD2, ADD3, ADD4, ADD5, OtherArgument_1, OtherArgument_2):
    tmp = df
    tmp['NEWADD'] = (tmp[ADD1] + ' ' + tmp[ADD2] + ' ' + tmp[ADD3] + ' ' + tmp[ADD4] + ' ' + tmp[ADD5]).str.strip()
2
  • you can check *args , **kwargs Commented Mar 17, 2021 at 19:07
  • 2
    I'm confused and I think I need to see an example to understand. Commented Mar 17, 2021 at 19:07

1 Answer 1

1

You can accomplish this by using loops and lists like this:

def myown(df, add_args, OtherArgument_1, OtherArgument_2):
    tmp = df
    new_add = ''
    for i in add_args:
        new_add = new_add + tmp[i].str.strip() + ''
        tmp['NEWADD'] = new_add

Your add_args parameter must be a list, which looks like this:

add_args = [ADD1, ADD2, ADDn]
Sign up to request clarification or add additional context in comments.

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.