我有一个excel文件作为参数文件,我在DataFrame中检索数据。
我迭代参数文件(并将参数存储在元组列表中)和dataframe,以便在适当时应用函数,但在参数文件中存储函数时,它的名称是字符串,它不工作。
我试过使用eval,但它没有返回。
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]]发布于 2021-09-21 11:20:21
可以使用vars()从本地命名空间获取对象。这将返回所有已定义对象的字典,包括函数。
>>> vars()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', 'Patient': <function Patient at 0x1007e52d0>, '__doc__': None, '__package__': None}您可以通过名称获取Patient函数,使用
fn = vars()['Patient'] # get the function.
fn() # call the function在您的代码中,这将成为。
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':
fn_name = v[3] # Get the name of the function.
fn = vars()[fn_name] # Get the function.
fn_arg = row[v[2]]
df.loc[index, v[0]] = fn(fn_arg) # Call the function.
else:
df.loc[index, v[0]] = row[v[2]]但请注意,你其实不需要这样做。既然您的函数名来自您的列表,那么为什么不直接将函数存储在其中呢?
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
('SEX',None,'dem_sex',Sex) *** Sex function
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':
fn = v[3] # Get the FUNCTION
fn_arg = row[v[2]]
df.loc[index, v[0]] = fn(fn_arg) # Call the function.
else:
df.loc[index, v[0]] = row[v[2]]在Python中,您可以将函数存储在列表中。
发布于 2021-09-21 10:54:11
你可以使用这样的东西:
class Functions():
def __init__(self):
pass
def alpha(self, a):
return a*2
obj = Functions()
call_this_function = getattr(obj, 'alpha')
print(call_this_function(2))https://stackoverflow.com/questions/69267502
复制相似问题