【发布时间】:2020-07-21 01:19:31
【问题描述】:
我有一个包含 8192 个元素的字符串列表,例如 my_list = ['10000', '00100', ..., '11101']。我想将每个元素拆分为一个字符并写入 excel 文件中的一行。也就是说,第一个元素'10000' 将是'1', '0', '0', '0', and '0',其中每个值将写入excel 文件的一列(以及其他两个值)。为此,我尝试将单个字符串类型转换为列表并使用 openpyxl 写入 excel 文件。
# run_experiment.py
import openpyxl as xl
import os
import time
result_source = "server_1"
n_instance = 50
'''
Some experiments will generate the `my_list` and one `time_stamp`.
`my_list` is actually a 2D list of strings i.e., list of list of strings
of dimension [n_instance] x [8192].
This `run_experiment.py` will be run a number of times
at different times of the day. For each run, therefore, the `time_stamp`
will be different.
'''
filepath = os.path.join(os.getcwd(), "memory_{}.xlsx".format(result_source))
if not os.path.exists(filepath):
wb = xl.Workbook()
ws = wb.active
first_row = ['Time Stamp', 'Result Source', 'Result-1',
'Result-2', 'Result-3', 'Result-4', 'Result-5']
ws.append(first_row)
wb.save(filename='memory_{}'.format(result_source))
wb = xl.load_workbook(filename = 'memory_{}.xlsx'.format(result_source))
ws = wb.active
for i in range(n_instance):
for j in range(8192):
row = list(my_list[i][j])
row.insert(0, result_source)
row.insert(0, time_stamp)
ws.append(row)
wb.save(filename='memory_{}.xlsx'.format(result_source))
但是,这种方法非常缓慢。由于我必须从多个result_source 写入数据,它变得更慢。有没有更快的方法来实现这一点?
【问题讨论】:
-
这就是你所做的一切,或者你的程序中是否有部分需要
openpyxl库?您可以使用pandas轻松完成此操作,但我不确定您的代码的其他部分是否可能需要来自openpyxl的功能,而这些功能在pandas中不可用。 -
openpyxl仅在此处使用。没有其他区块需要openpyxl。 -
代码不完整,但在编辑现有文件时,选项有些受限。您可以通过一步创建列表来获得一些改进:
[timestamp, result_source] + list(my_list[i])。 (并直接遍历列表)。 -
在这里使用 Pandas 并没有真正的帮助,因为您必须从 openpyxl 转换为 pandas 并返回。
-
@CharlieClark 我已经编辑了代码以使其更完整。
标签: python python-3.x excel split openpyxl