Pandas to_dict("records") seems to have a much inferior performance compared to a naive implementation. Below is the code snippet of my implementation:
def fast_to_dict_records(df):
data = df.values.tolist()
columns = df.columns.tolist()
return [
dict(zip(columns, datum))
for datum in data
]
To compare the performance, try the below code snippet:
import pandas as pd
import numpy as np
df_test = pd.DataFrame(
np.random.normal(size=(10000, 300)),
columns=range(300)
)
%timeit df_test.to_dict('records')
%timeit fast_to_dict_records(df_test)
And the outputs are:
2.21 s ± 71.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
293 ms ± 15.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Namely my implementation is ~7.5 faster than pandas native implementation. Also, it should be easy to verify that the two methods provide the same result. I have also tested the performance against different sizes of dataframes and seems like my implementation is consistently outperform its counterpart (although the magnitude might differ).
I am curious am I missing anything here? I am just not convinced that pandas native implementation performance, which under my impression was quite competitive, can be beaten that much by a not-so-complicated alternative...