我正在像这样读取一堆SAS文件:
demography = pd.read_sas("demography.sas7bdat", encoding = 'latin-1')
adverse_event_ds = pd.read_sas("adverse_event_ds.sas7bdat", encoding = 'latin-1')
rpt10344 = pd.read_sas("rpt10344.sas7bdat", encoding = 'latin-1')
vaccine_administration = pd.read_sas("vaccine_administration.sas7bdat", encoding = 'latin-1')
lab_tests_blood_chemistry_ds = pd.read_sas("lab_tests_blood_chemistry_ds.sas7bdat", encoding = 'latin-1')
lab_tests_hematology_ds = pd.read_sas("lab_tests_hematology_ds.sas7bdat", encoding = 'latin-1')
lab_tests_miscellaneous_ds = pd.read_sas("lab_tests_miscellaneous_ds.sas7bdat", encoding = 'latin-1')
vital_signs = pd.read_sas("vital_signs.sas7bdat", encoding = 'latin-1')
我希望能够将其替换为以下内容:
datasets = ["demography", "adverse_event_ds", "rpt10344", "vaccine_administration", "lab_tests_blood_chemistry_ds", "lab_tests_hematology_ds", "lab_tests_miscellaneous_ds", "vital_signs"]
for dataset in datasets:
dataset = pd.read_sas(dataset+".sas7bdat", encoding = 'latin-1')
但是当我做类似的事情时:
demography.info()
我得到:
NameError: name 'demography' is not defined
引擎盖下发生了什么,我该如何解决?
答案 0 :(得分:2)
这是在每次迭代时分配给dataset
,而不是创建新变量(例如demography
,rpt10344
等)。
我将按照以下方式使用数据集字典:
dsd = {}
for dataset in datasets:
dsd[dataset] = pd.read_sas(dataset+".sas7bdat", encoding = 'latin-1')
或更Python化的路线:
dsd = { d : pd.read_sas(d + ".sas7bdat", encoding = 'latin-1') for d in datasets }
出于here和here的解释,我强烈建议不要分配给各个变量名称,但是如果您绝对必须可以使用
for d in datasets:
globals()[d] = pd.read_sas(d + ".sas7bdat", encoding = 'latin-1')