Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Custom function creation: How to skip first line of 'if' statement based on input parameters?

I have created a custom function designed to append columns onto an existing data frame based on user inputs. However, if the last variable is set to the None argument, I want the if-else statement to end. However, if it is set to something else (a string), I want the statement to continue. How can I properly format my if-else statement for this?

Here is the data:

import pandas as pd

data = {'col1':['a','b','c','d','e','f','g'],
        'foo':[1,2,3,4,5,6,7],
        'bar':[8,9,10,11,12,13,14],
        'foobar':[15,16,17,18,19,20,21]}

df = pd.DataFrame(data)
df

Here is my function:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def func(a, b, c, d):
    """
    Parameters
    ---------------
    a = String
        name of col 2 in data frame
    b = String
        name of col 3 in data frame
    c = String
        name of col 4 in data frame
    d = String
        Name of last desired output column. Can assign None if nothing is desired.
        
    Returns:
    ---------------
    Input data frame with appended columns
    
    Example:
    ---------------
    func('foo', 'bar', 'foobar', 'lastcol')
    """
    df['new_col1'] = df[a] + 44
    df['new_col2'] = df[b] + 88
    df['new_col3'] = df[c] + 133
        
    if d == None:
        continue
    else:
        df[d] = df[a] + df[b]
        
    return df.head(5)

The following error is produced:

  Input In [20]
    continue
    ^
SyntaxError: 'continue' not properly in loop

>Solution :

continue is used inside a for-loop or a while-loop.
to termiante the function you could do:

if d is not None:
    df[d] = df[a] + df[b]
    return df.head(5)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading