python - 优化 os.walk() 迭代;在 64 位、4 核、64 GB、2.50GHz 系统上
问题描述
我有一个 64 位、4 核、2.50GHz、64GB 系统和 13GB 可用内存。我正在尝试使用以下代码读取 24 个 csv 约 4000 万行;
def test():
test = pd.DataFrame()
rootdir ='/XYZ/A'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
df = pd.read_csv(os.path.join(subdir, file), low_memory=False)
test = pd.concat([test, df])
return test
我怎样才能优化它以更快地运行,而不会导致内核死亡。我应该在 Pyspark 中实现这个吗???如果我错过任何细节,请告诉我。
解决方案
试一试,我使用了pathlib模块,因为它提供了更简洁和更清晰的代码恕我直言,并且您可以利用迭代器和生成器表达式:
from pathlib import Path
def test():
rootdir ='/XYZ/A'
#assumption is that they are all csvs
#if not. u could just use rglob('*.*')
#this will recursively search through the directory
#and pull all files with the extension csv
#or all files if u use ('*.*')
#which might be a bit more intensive computation
all_files = Path(rootdir).rglob('*.csv')
all_dfs = (pd.read_csv(f)
#kindly test this aspect and c
#stem gets u the name before '.csv'
#and returns a string
#rsplit splits based on the last '_'
.assign(Date = f.stem.rsplit('_')[-1])
for f in all_files)
#trying to delay the intense computation till it gets here
#hence the use of generator expressions
final_df = pd.concat(all_dfs,ignore_index=True)
return final_df
让我们知道它是怎么回事;如果它失败了,我会把它取下来,以免混淆其他人。
推荐阅读
- python - 单击一个元素以使用 python 网络抓取动态更改内容
- discord.js - Autorole 使用用户定义的角色
- python - 使用 pandas 数据框中的城市名称向 folium 地图添加多个标记
- json - 如何将 Bloodhound 与使用烧瓶 jsonify 创建的 JSON 一起使用
- php - Mediawiki job is claimed but not processed
- c++ - 使用 hashmap 进行相对排序
- python - 在 for 循环中使用 tf.concat 添加值是否很慢?
- azure-functions - Azure 函数安全 - 仅允许逻辑应用
- getusermedia - 移动设备上的 getUserMedia(自拍)全屏
- html - 替换为取决于找到的字符串