我正在尝试阅读12个单独的CSV文件,并希望使用for循环来执行此操作。出于某种原因,代码似乎无法正常工作:
files = ['Jan2016', 'Feb2016', 'Mar2016', 'Apr2016', 'May2016', 'Jun2016', 'Jul2016', 'Aug2016', 'Sep2016', 'Oct2016', 'Nov2016', 'Dec2016']
for file in files:
file = pd.read_csv("/Volumes/Toshiba/PrescriptionData/Results2/" + i + ".csv")
print(Jan2016)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-49-906109eb8ce9> in <module>()
4 file = pd.read_csv("/Volumes/Toshiba/PrescriptionData/Results2/" + i + ".csv")
5
----> 6 print(Jan2016)
NameError: name 'Jan2016' is not defined
但是,当我输入print(文件)时,代码会编译并打印Dec2016 CSV文件中的数据(即我的文件&#39;列表中的最终值)。关于为什么这个for循环不起作用的任何想法?
答案 0 :(得分:0)
对于DataFrames字典,您需要pop ip
:
pop
与...相同:
dict comprehension
然后按键选择path = "/Volumes/Toshiba/PrescriptionData/Results2/"
dfs = {file : pd.read_csv(path + file + ".csv") for file in files}
:
dfs = {}
path = "/Volumes/Toshiba/PrescriptionData/Results2/"
for file in files:
dfs[file] = pd.read_csv(path + file + ".csv")