Python,Dict to CSV:有没有更快的方法可以做到这一点



我写了一个简单的方法来将字典写入CSV。

它运行良好,但我想知道是否可以在速度方面提高它(在我的测试中编写 1000 行的 CSV 需要 6 秒(。

我的问题是:如何提高这段代码的速度?(如果可能的话(

提前感谢您的帮助。

def fast_writer(self, f_name, text_dict):
    try:
        start = timer()
        # Windows
        if os.name == "nt":
            with open(f_name, 'w', newline='') as self._csv_file:
                self._writer = csv.writer(self._csv_file)
                for self._key, self._value in text_dict.items():
                    self._writer.writerow([self._key, self._value])
        # Unix/Linux
        else:
            with open(f_name, 'w') as self._csv_file:
                self._writer = csv.writer(self._csv_file)
                for self._key, self._value in text_dict.items():
                    self._writer.writerow([self._key, self._value])
        end = timer()
        print("[FastWriter_time] ", end - start)
    except BaseException:
        print("[ERROR] Unable to write file on disk. Exit...")
        sys.exit()

如果您真的只是在寻找一种更快的方法来执行此操作,pandas内置了这样的方法,并且优化得很好!以以下代码为例:

import numpy as np
import pandas as pd
# This is just to generate a dictionary with 1000 values:
data_dict = {'value':[i for i in np.random.randn(1000)]}
# This is to translate dict to dataframe, and then same it
df = pd.DataFrame(data_dict)
df.to_csv('test.csv')
将字典写入数据帧

并将数据帧写入计算机上的 csv 大约需要 0.008 秒

如果你不想使用 pandas ,去掉所有存储在 self 中的变量,并使它们成为局部变量:

def fast_writer(self, f_name, text_dict):
    try:
        start = timer()
        newline = '' if os.name == "nt" else None
        with open(f_name, 'w', newline=newline) as csv_file:
            writer = csv.writer(csv_file)
            writer.writerows(text_dict.items())
        end = timer()
        print("[FastWriter_time] ", end - start)
    except BaseException as e:
        print("[ERROR] Unable to write file on disk. Exit...")
        print(e)
        sys.exit()

此外,使用 writer.writerows 一次写入多行。

在我的机器上,这比pandas方法更快,使用@sacul在其答案中定义的测试数据:

In [6]: %timeit fast_writer("test.csv", data_dict)
1.59 ms ± 62.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [10]: %timeit fast_writer_pd("test.csv", data_dict)
3.97 ms ± 61.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Writer 对象已经有一个将行列表写入文件的方法;不需要显式迭代。

def fast_writer(self, f_name, text_dict):
    try:
        start = timer()
        with open(f_name, 'w', newline=None) as csv_file:
            writer = csv.writer(csv_file)
            writer.writerows(text_dict.items())
        end = timer()
        print("[FastWriter_time] ", end - start)
    except Exception:
        print("[ERROR] Unable to write file on disk. Exit...")
        sys.exit()

几点意见:

  1. 您无需嗅探操作系统; newline=None使用基础系统默认值。
  2. 如果要在每次调用时重新分配self._writerself._csv_file,它们可能不必是实例属性;它们可以只是局部变量:writer = csv.writer(csv_file)
  3. BaseException太宽泛了;它并不比一个赤裸裸的except陈述更好。使用 Exception ,但请考虑只捕获IOError并改为OSError。其他异常可能表示代码中的错误,而不是合法的 IO 错误。

相关内容

最新更新