在panda中连接或附加巨大的多个xlsx文件的最佳有效方式



熊猫在自我学习方面取得了一些进展,所以我想要最好、有效的方法来处理这个问题:

我有3个有时超过3个excel文件";。xlsx";每个大约100MB,每个文件和200列至少有800K条记录。

这些文件完全共享相同的列,它们被拆分,因为它们是从一个无法组合处理所有列的系统中导出的。

我想在一个数据帧中加载文件,打开每个文件,然后打开concatappend。我知道这将取决于机器的内存,但我正在寻找在一个帧中处理这些文件并控制它们的最佳方法。

这就是我所拥有的:

start = timeit.default_timer()
all_data = pd.DataFrame()
for f in glob.glob("./data/*.xlsx"):
df = pd.read_excel(f)
all_data = all_data.append(df,ignore_index=True)

all_data
stop = timeit.default_timer()
execution_time = stop - start
print (execution_time)

使用append,在dfall_data中加载文件大约需要7分钟

有没有最好的方法可以在更短的时间内加载它们?

您可以使用multiprocessing来提高加载速度,并使用concat合并所有dfs:

import pandas as pd
import multiprocessing
import glob
import time

def read_excel(filename):
return pd.read_excel(filename)

if __name__ == "__main__":
files = glob.glob("./data/*.xlsx")
print("Sequential")
print(f"Loading excel files: {time.strftime('%H:%M:%S', time.localtime())}")
start = time.time()
data = [read_excel(filename) for filename in files]
end = time.time()
print(f"Loaded excel files in {time.strftime('%H:%M:%S', time.gmtime(end-start))}")
df_sq = pd.concat(data).reset_index(drop=True)
print("Multiprocessing")
with multiprocessing.Pool(multiprocessing.cpu_count()) as pool:
print(f"Loading excel files: {time.strftime('%H:%M:%S', time.localtime())}")
start = time.time()
data = pool.map(read_excel, files)
end = time.time()
print(f"Loaded excel files in {time.strftime('%H:%M:%S', time.gmtime(end-start))}")
df_mp = pd.concat(data).reset_index(drop=True)

示例:50个25MB的文件(增加2倍(

Sequential
Loading excel files: 09:12:17
Loaded excel files in 00:00:14
Multiprocessing
Loading excel files: 09:12:33
Loaded excel files in 00:00:07

最新更新