Python+不同的数据存储方式比较

本文来探索一下python中提供的各种数据保存格式的性能如何。主要以一个 ndarray 格式的数据进行处理分析。包括下面几种方式:

  • .bin格式, np.tofile() 和 np.fromfile()
  • .npy格式,np.save() 和 np.load()
  • .txt 或者 .csv格式,np.savetxt() 和 np.loadtxt()
  • .h5 格式,h5py.File(,’r’ 或者 ‘w’)
  • .pkl 格式, pickle.dump()和pickle.load()
import numpy as np
from __future__ import print_function
import time
a = np.random.randint(0, 100, size=(10000, 5000))
print(a.dtype, a.shape)
print(a[:2])
int64 (10000, 5000)
[[90 96 38 ..., 67 40 79]
 [40 12 71 ..., 64 76 15]]

1. np.tofile() 和 np.fromfile()

%time a.tofile('data/a.bin')
%time b = np.fromfile('data/a.bin', dtype=np.int64)
print(b.shape)
print(b[:2])
CPU times: user 4 ms, sys: 392 ms, total: 396 ms
Wall time: 2.06 s
CPU times: user 4 ms, sys: 156 ms, total: 160 ms
Wall time: 160 ms
(50000000,)
[90 96]
  • 读入数据的时候要正确设置 dtype 参数

  • 读入的数据是一维的,还需要经过 reshape 处理。

2. np.save()和np.load()

%time np.save('data/a.npy', a)
%time b = np.load('data/a.npy')
print(b.shape)
pr
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值