熊猫新手在自学方面取得了一些进展,所以我想要最好、最有效的方法来处理这个问题:
我有 3 个有时超过 3 个 excel 文件“.xlsx”,每个文件大约 100MB,每个文件至少有 800K 记录和 200 列。
这些文件完全相同地共享相同的列,它们被分割,因为它们是从无法处理所有这些文件组合的系统导出的。
我想将文件加载到一个数据框中,打开每个数据帧,然后concat
or append
我知道这取决于机器的内存,但我正在寻找处理这些文件并在一帧中控制它们的最佳方法。
这就是我所拥有的:
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,加载df中的文件大约需要7分钟all_data
有没有最好的方法来在更短的时间内加载它们?
您可以使用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)
Example: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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)