这不是一个确切的答案,但下面是各种针对您这类数据的方法的更详细的基准测试...
import timeit
import numpy as np
import pandas as pd
from numpy.random import randn, randint
def generate_data(n):
df = pd.DataFrame(
{
"dt": randint(1_600_000_000, 1_700_000_000, size=n) * 1000,
"a": randn(n),
"b": randn(n),
"c": randn(n),
}
)
df.dt = pd.to_datetime(df.dt, unit="s")
df.set_index("dt", inplace=True)
return df
def benchmark(df, name, saver, loader):
verify(df, loader, saver)
save_timer = timeit.Timer(lambda: saver(df))
load_timer = timeit.Timer(lambda: loader().a.sum())
save_n, save_time = save_timer.autorange()
load_n, load_time = load_timer.autorange()
total_time = (load_time / load_n) + (save_time / save_n)
print(
f"{name:<15s} : "
f"{save_n / save_time:>20.3f} save/s : "
f"{load_n / load_time:>20.3f} load+sum/s : "
f"{1 / total_time: >20.3f} total speed"
)
def verify(df, loader, saver):
saver(df)
loaded = loader()
assert np.allclose(loaded.a.sum(), df.a.sum())
assert np.allclose(loaded.b.sum(), df.b.sum())
assert list(loaded.columns) == list(df.columns), loaded.columns
def save_feather(df):
df = df.reset_index()
df.to_feather("dummy.feather")
def load_feather():
df = pd.read_feather("dummy.feather")
df.set_index("dt", inplace=True)
return df
def main():
df = generate_data(5_000_000)
benchmark(df, "dummy", lambda df: None, lambda: df)
benchmark(df, "csv", lambda df: df.to_csv("dummy.csv"), lambda: pd.read_csv("dummy.csv", index_col="dt"))
benchmark(df, "hdf", lambda df: df.to_hdf("dummy.h5", "dummy"), lambda: pd.read_hdf("dummy.h5", "dummy"))
benchmark(df, "pickle", lambda df: df.to_pickle("dummy.pickle"), lambda: pd.read_pickle("dummy.pickle"))
benchmark(df, "feather", save_feather, load_feather)
benchmark(
df,
"parquet",
lambda df: df.to_parquet("dummy.parquet", allow_truncated_timestamps=True),
lambda: pd.read_parquet("dummy.parquet"),
)
if __name__ == "__main__":
main()
在我的电脑上(Ryzen 7 3700X, SSD硬盘, Windows 10, Python 3.8, 最新的Pandas等)和一个百万行的数据框(没耐心等待CSV结果),我得到了:
dummy : 10475677.467 save/s : 186.737 load+sum/s : 186.734 total speed
csv : 0.185 save/s : 0.970 load+sum/s : 0.156 total speed
hdf : 18.289 save/s : 28.514 load+sum/s : 11.142 total speed
pickle : 14.058 save/s : 31.962 load+sum/s : 9.764 total speed
feather : 34.766 save/s : 41.436 load+sum/s : 18.904 total speed
parquet : 7.707 save/s : 19.603 load+sum/s : 5.532 total speed
因此,HDF5绝对不会快上几个数量级。