I have a large dataframe with multi-index. I wanted to slice this dataframe using a fairly large list. Below is a sample code. It is taking almost 10 seconds for this operation.
import pandas as pd
import numpy as np
df = pd.DataFrame(
{
"x": np.repeat(np.arange(10000), 50),
"y": np.repeat(np.arange(50), 10000),
"val": np.random.rand(50*10000)
}
).set_index(["x", "y"])
large_list = range(5000,10000)
slice = df.loc[(large_list, slice(None)),:] # Takes 10 seconds on my machine
As a comparison, if I write this dataframe to an hdf file and read it with a where condition same as my slicing operation, it takes only 1.5 seconds!
df.to_hdf("sample.hdf", key="df", append=True)
df1 = pd.read_hdf("sample.hdf", "df", where='x in large_list')
Is there a faster way to slice in memory?