首先,我导入一个名为file_1
,...,file_25
的文件至25个文件;如果我导入七个,则可以是file_1
到file_7
,也可以是其他任何文件。
接下来,我将它们合并为一个。我是通过
files = ["file_1","file_2","file_3","file_4","file_5","file_6","file_7","file_8","file_9","file_10","file_11","file_12","file_13","file_14","file_15","file_16","file_17","file_18","file_19","file_20","file_21","file_22","file_23","file_24","file_25"]
all_files = pd.DataFrame()
for file in files:
if file in globals():
print("Merging", file)
all_files = all_files.append(eval(file))
else:
print(file, "not in globals")
(供以后的读者注意:列表files
可以通过Excel轻松创建;无需全部输入)
为避免内存错误,我然后要删除所有现有文件。我在想类似的东西
a = 1
b = 2
c = 3
l = [a,b,c]
for l in l:
del l
但它不起作用(我知道还没有条件检查其中是否存在,但是如果列表中的所有文件都存在,它也将不起作用。 该如何解决?
编辑: 完整示例:
file_1 = pd.read_csv("path/file_1")
file_2 = pd.read_csv("path/file_2")
file_3 = pd.read_csv("path/file_3")
file_4 = pd.read_csv("path/file_4")
file_5 = pd.read_csv("path/file_5")
file_6 = pd.read_csv("path/file_6")
file_7 = pd.read_csv("path/file_7")
file_8 = pd.read_csv("path/file_8")
file_9 = pd.read_csv("path/file_9")
file_10 = pd.read_csv("path/file_10")
file_11 = pd.read_csv("path/file_11")
file_12 = pd.read_csv("path/file_12")
file_13 = pd.read_csv("path/file_13")
file_14 = pd.read_csv("path/file_14")
file_15 = pd.read_csv("path/file_15")
file_16 = pd.read_csv("path/file_16")
file_17 = pd.read_csv("path/file_17")
file_18 = pd.read_csv("path/file_18")
file_19 = pd.read_csv("path/file_19")
file_20 = pd.read_csv("path/file_20")
file_21 = pd.read_csv("path/file_21")
file_22 = pd.read_csv("path/file_22")
file_23 = pd.read_csv("path/file_23")
file_24 = pd.read_csv("path/file_24")
file_25 = pd.read_csv("path/file_25")
files = ["file_1","file_2","file_3","file_4","file_5","file_6","file_7","file_8","file_9","file_10","file_11","file_12","file_13","file_14","file_15","file_16","file_17","file_18","file_19","file_20","file_21","file_22","file_23","file_24","file_25"]
all_files = pd.DataFrame()
for file in files:
if file in globals():
print("Merging", file)
all_files = all_files.append(eval(file))
else:
print(file, "not in globals")
# How to simplfy the following?
del file_1
del file_2
del file_3
del file_4
del file_5
del file_6
del file_7
del file_8
del file_9
del file_10
del file_11
del file_12
del file_13
del file_14
del file_15
del file_16
del file_17
del file_18
del file_19
del file_20
del file_21
del file_22
del file_23
del file_24
del file_25
我希望能够导入文件的子集,但仍然具有自动执行的以下步骤(将它们放入一个变量并删除单个文件)。我成功完成了第一步(将它们放入一个变量),但是没有完成第二步(删除单个文件)。 我想以某种方式循环遍历变量并检查它们是否存在;如果有,请删除它们。该怎么做?