python - 有没有更好的方法来加快 Pandas 读取 csv 文件的速度?
问题描述
操作系统:macOS High Sierra,版本 10.13.1 Xcode 中的 Python 3.6
我正在使用 pandas 和传统 python 的 csv 模块读取一个 csv 文件。显然,csv 模块比 pandas 快得多。我知道 pandas 会进行 NaN 检查,但我有两个问题:(i)有没有办法加快 pandas 的速度?(ii) 在 pandas 上使用 python 的 csv 模块有缺点吗?
我的代码:
def read_pd():
path=os.getcwd()
filename="Sen_01_sample.csv"
filePathname=path +"/"+filename
#print('reading...')
data=pd.read_csv(filePathname,nrows=11,engine="c",skiprows=0)
#print('read')
def read_csv():
path=os.getcwd()
filename="Sen_01_sample.csv"
filePathname=path+"/"+filename
with open(filePathname,mode='r') as csvfile:
csvread=csv.reader(csvfile)
col_count=len(next(csvread))
row_count = sum(1 for row in csvread)
#print(row_count)
#print(col_count)
csvfile.seek(0)
data=np.zeros((row_count-1,col_count-5),dtype=np.float32)
row=0
line_count=0
for rows in csvread:
if line_count ==0:
dummy=0
else:
data[row]=np.array(rows[4:-1],dtype=np.float32)
#print (data[row][-1])
line_count+=1
计时结果:
Time to read a csv file from Pandas 130.997ms.
Time to read a csv file using Python's native csv module 15.448ms.
Python csv module reads file at 11.79% of the time taken by Pandas.
解决方案
推荐阅读
- linux - VboxManage list vms Linux Shell Script 总是输出错误的结果
- java - Calcu:如何像真正的计算一样在每个数字之前添加运算符
- python - 使用正则表达式从 HTML 中提取所有值
- java - 2D 图形问题 - 可能是逻辑
- php - 使用 Guzzle 向 API 发送数据时无法解码 json 错误
- android - Google Nearby Connections - 如何使用流发送大数据字符串?
- java - 使用 Apache Camel 设置 RabbitMQ 消息属性
- google-apps-script - 在哪里可以找到 Google Apps 脚本支持的语法?
- c# - C#列表项值不一致
- android - 如何将 Kotlin 内联类与 Android 数据绑定集成?