繁体   English   中英

Python,从CSV转换为Dict:是否有更快的方法?

[英]Python, Dict to CSV: is there a faster way to do it?

我编写了一种简单的方法,可以将字典写入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')

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

如果您不想使用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是一个空洞的except声明。 使用Exception ,但请考虑只捕获IOErrorOSError 其他异常可能表明您的代码中存在错误,而不是合法的IO错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM