Iterate over each row of a files where functions names are stored and call the function

  function, pandas, python

I have a excel file I use as parameters file and I retrieve data in a DataFrame

I iterate over parameters file (and store parameters in list of tuples) and dataframe to apply function when appropriate but as function is stored in paramtres files by its name which is a string it doesn’t work

I tried using eval but it return None


def Patient(pat_ide):
    return '0' + str(pat_ide[4:])

def Sex(code):
    if code == 1:
        return 'M'
    else:
        return 'F'

# extract parameters from excel files
sdtm = [
    ('STUDYID','01-COV',None,None), 
    ('DOMAIN','DM',None,None), 
    ('USUBJID',None,'pat_ide',None), 
    ('SUBJID',None,'pat_ide','Patient'),    *** Patient function BUT STRING ***
    ('SEX',None,'dem_sex','Sex')            *** Sex function BUT STRING ***
]

for v in sdtm:
    for index, row in df.iterrows():
        # if assigned value
        if v[1] != 'NULL':
            df.loc[index, v[0]] = v[1]
        # else retrieve value from raw data
        else:
            if v[3] != 'NULL':
                df.loc[index, v[0]] =  eval('%s(%s)'%(v[3],row[v[2]]))  *** return None ***
            else:
                df.loc[index, v[0]] = row[v[2]]

Source: Python Questions

LEAVE A COMMENT