Python,Dict to CSV:有没有更快的方法?
我已经写了一个简单的方法来将字典写入CSV 它工作得很好,但我想知道它在速度方面是否可以改进(在我的测试中,编写1000行的CSV需要6秒) 我的问题是:如何提高此代码的速度?(如果可能) 提前感谢您的帮助Python,Dict to CSV:有没有更快的方法?,python,python-3.x,performance,csv,Python,Python 3.x,Performance,Csv,我已经写了一个简单的方法来将字典写入CSV 它工作得很好,但我想知道它在速度方面是否可以改进(在我的测试中,编写1000行的CSV需要6秒) 我的问题是:如何提高此代码的速度?(如果可能) 提前感谢您的帮助 def fast_writer(self, f_name, text_dict): try: start = timer() # Windows if os.name == "nt": with open(f_n
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内置了这样的方法,并且进行了很好的优化!以以下代码为例:
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
方法快:
如果您不想使用
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
方法快:
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()
几点意见:
newline=None
使用基础系统默认值self.\u writer
和self.\u csv\u file
,它们可能不必是实例属性;它们可以只是局部变量:writer=csv.writer(csv\u文件)
BaseException
过于宽泛;它不比一个简单的语句好多少,除了语句。使用<代码>异常< /代码>,但只考虑捕获<代码> IOError < /代码>和<代码> OSError <代码>。其他异常可能表示代码中存在错误,而不是合法的IO错误
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()
几点意见:
newline=None
使用基础系统默认值self.\u writer
和self.\u csv\u file
,它们可能不必是实例属性;它们可以只是局部变量:writer=csv.writer(csv\u文件)
BaseException
过于宽泛;它不比一个简单的语句好多少,除了语句。使用<代码>异常< /代码>,但只考虑捕获<代码> IOError < /代码>和<代码> OSError <代码>。其他异常可能表示代码中存在错误,而不是合法的IO错误
至少在我的机器上,简单的Python方式比这更快。可能是因为首先将数据读入数据帧的开销。我想最终它会受到磁盘写入速度的限制。只是检查一下-数据不是只记录一行吗?至少在我的机器上,普通Python方式比这快。可能是因为先将数据读入数据帧的开销。我想最终它会受到磁盘写入速度的限制。只是检查一下——数据不是只有一行吗?