What I need is to get the unique date value as soon as possible.
I use the code df = store.df.date.drop_duplicates() to retrieve. This line of code takes 6 seconds. However, if I use mysql and save the same data to mysql, I use mysql for the date column After indexing, using sql:select distinct date from table, it only takes 80ms to retrieve the unique date value, which is 60 times faster than HDF5.
Is there any way to make the function read_unique_date read HDF5 faster than MySQL uses indexes?
My code is as follows:
import pandas as pd
import numpy as np
from itertools import product
from time import time
def generate_data():
np.random.seed(202108)
# date = pd.date_range(start="19900101", end="20210723", freq="D")
#The above is my original code, you can use the following code to speed up the operation.
date = pd.date_range(start="20210101", end="20210723", freq="D")
date = pd.DataFrame(date, columns=["date"])
# code = pd.DataFrame(range(5000), columns=["code"])
#The above is my original code, you can use the following code to speed up the operation.
code = pd.DataFrame(range(50), columns=["code"])
# generate product of the two columns:
df = pd.DataFrame(product(date["date"], code["code"]), columns=["date", "code"])
df['data'] = np.random.random(len(df))
return df
def save_data(filename, df):
store = pd.HDFStore(filename)
store['df'] = df
store.close()
return
def read_unique_date(file_name):
store = pd.HDFStore(file_name)
start = time()
df = store.df.date.drop_duplicates()
store.close()
stop = time()
print(stop - start)
return df
def main():
path = 'd:\\'
file = 'large data.h5'
file_name = path + file
df = generate_data()
save_data(file_name, df)
df1 = read_unique_date(file_name)
print(df1)
return df1
if __name__ == '__main__':
main()
The result is:
0.015624761581420898
0 2021-01-01
50 2021-01-02
100 2021-01-03
150 2021-01-04
200 2021-01-05
...
9950 2021-07-19
10000 2021-07-20
10050 2021-07-21
10100 2021-07-22
10150 2021-07-23
Name: date, Length: 204, dtype: datetime64[ns]
%timeit df1 = read_unique_date(file_name)
16.9 ms ± 200 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
The result of my original code:
%timeit df1 = read_unique_date(file_name)
4.89 s ± 119 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)