Fastest way to write BIG pandas DataFrame

Viewed 3091

I ran a test which tested 10 ways to write and 10 ways to read a DataFrame. I found the test here (I made some ajustements and added Parquet to the list) The best ways were :

df.to_feather('test.feather') :
39.34544535900204s

table=pyarrow.Table.from_pandas(df)
pq.write_table(table, "test_parquet_write_snappy_dict.parquet",
               use_dictionary=True, version='2.0', compression='snappy') :
40.6873751259991s

table=pyarrow.Table.from_pandas(df, nthreads=4)
pq.write_table(table, "test_parquet_write_snappy_dict.parquet",
               use_dictionary=True, version='2.0', compression='snappy') :
41.051620177000586s

for the writing

and

pd.read_hdf('test_fixed.hdf', 'test') :
1.5275615360005759

pd.read_feather('test.feather') :
20.635139821002667

pd.read_pickle('test.pkl') :
37.21131302599679

for the reading.

Here's the DataFrame :

sz = 50000000
df = pd.DataFrame({'A': randn(sz), 'B': randn(sz), 'C': randn(sz), 'D': randn(sz)})

I have two questions. How read_hdf is 20 times fastest than read_feather while to_hdf isn't even in the first three of the write tests ?

And second one, 40 seconds is still too slow for my needs. Would there be a way to improve that speed ? Either by using different parameters with to_feather or write_table or using a function/module I doesn't know about ?

I'm not asking for someone to look up for me, I can do this myself and I don't want to waste anybody's time. I'm looking for someone who already know this problem and could lead me to the fastest way he knows.

1 Answers

It's not exactly an answer per se, but here's a more thorough benchmark of various methods for data like yours...

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()

On my box (Ryzen 7 3700X, SSD disk, Windows 10, Python 3.8, newest Pandas and such) and a million-row DF (couldn't be bothered to wait for CSV results), I get

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

so HDF5 definitely isn't orders of magnitude faster.

Related