Home > Mobile >  Custom function creation: How to skip first line of 'if' statement based on input paramete
Custom function creation: How to skip first line of 'if' statement based on input paramete

Time:03-12

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:

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

CodePudding user response:

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)

CodePudding user response:

Why not instead of

    if d == None:
        continue
    else:
        df[d] = df[a]   df[b]

...just do this:

    if d is not None:
        df[d] = df[a]   df[b]
  • Related