python-3.x - 将调用不同函数的 for 循环转换为生成器
问题描述
我正在阅读 csv 列表、执行计算并将输出写入驱动器。数据集很大(16gb RAM 上 2gb csv),计算成本高,输出也很大。因此我想使用发电机;这样我就可以一次写一个输出文件。我使用的功能很大,因此不在此处粘贴。我认为带有最终 for 循环的生成器可以完成这项工作。
#read csv with indexing, uecols, dtypes ~ 1 DF is approx 50mb in memory
def reader_1sec_csv(filepath,.....):
return pd.read_csv(filepath,........)
#processing df
def booleans (dataframe):
dataframe = dataframe[....]
....
....
return dataframe
#processing, row by row operation
def activity (row):
val = "Unknown"
...
...
return val
#apply the functions to a list of filepaths and write to outdir
def csv_to_result (filepath, outdir =".."):
dataframe = booleans(reader_1sec_csv(filepath))
dataframe["Activity"] = dataframe.apply(activity, axis=1)
out = dataframe[["Activity"]]
out.to_csv(os.path.join(outdir, os.path.splitext(os.path.basename(filepath))[0]+'_A.csv'))
#Can I make this into a generator? Keeping the exceptions list?
exceptions = []
for i in filepaths:
try:
csv_to_outcsv(i)
except:
exceptions.append(i)
continue
解决方案
我正在附加例外列表。所以我使用time
模块将程序设置为每 5 分钟运行一次。因为在生成器中定义所有异常并不容易。
exceptions_list = []
def gen_out(paths):
for i in paths:
try:
yield csv_to_outcsv(i)
except:
exceptions_list.append(i)
continue
def periodic_work(interval):
while True:
next(gen_out(filepaths)
time.sleep(interval)
推荐阅读
- android - 如何在 Android 样式中更改字体类型、字体大小和粗体文本 (PopUpMenu)
- javascript - 带有 if 语句的 chart.js 标签
- angular - 如何在 Angular 表单中禁用按钮
- javascript - 默认情况下,必须在页面加载时选择 html 单选按钮
- clips - CLIPS 规则不匹配
- python - 程序未读取“?” 用“?”分隔字符串后 也 '。'
- r - R遍历一组列以制作多个图
- discord - 如何让 discord.js 机器人回复 DM 但只回复一次
- javascript - 如何根据变量过滤打字稿数组
- javascript - Safari iframe hasStorageAccess,但从它的非 iframed url 输出不同的 localStorage