from pandas import DataFrame
import time
data = []
for i in range(3000):
data.append(['SH601318', 'abcdef', 0.0001215, 0.000215, 0.125, 0.243])
df = DataFrame(data)
df.columns = ['symbol', 'name', 'total_ratio', 'outstanding_ratio', 'avg_total_ratio', 'avg_outstanding_ratio']
t = time.time()
result = [{
'symbol': df.at[i, 'symbol'],
'name': df.at[i, 'name'],
'total_ratio': df.at[i, 'total_ratio'],
'outstanding_ratio': df.at[i, 'outstanding_ratio'],
'avg_total_ratio': df.at[i, 'avg_total_ratio'],
'avg_outstanding_ratio': df.at[i, 'avg_outstanding_ratio'],
} for i in range(len(df))]
print '%.2f seconds' % (time.time() - t)
# 0.25 seconds
t = time.time()
result = [df.iloc[i].to_dict() for i in range(len(df))]
print '%.2f seconds' % (time.time() - t)
# 0.58 seconds
我尝试了两种方法将DataFrame转换为dict列表。但两者都很慢,250毫秒和580毫秒!这远远超过我从数据库查询的时间。我不知道为什么需要这么多时间,毕竟操纵内存比磁盘更快。我预计这个时间是10毫秒。有什么办法可以实现吗?