Description
Pandas version checks
-
I have checked that this issue has not already been reported.
-
I have confirmed this bug exists on the latest version of pandas.
-
I have confirmed this bug exists on the main branch of pandas.
Reproducible Example
def make_data():
dates = pd.date_range("2001", "2020")
ids = [f"id_{i + 1}" for i in range(1000)]
index = pd.MultiIndex.from_product([dates, ids], names=["date", "id"])
columns = [f"col_{i + 1}" for i in range(10)]
return pd.DataFrame(0.0, index=index, columns=columns)
if __name__ == "__main__":
frame = make_data()
t0 = frame.index.get_level_values("date").min()
end = pd.date_range("2001", "2020", freq="M")
m = psutil.Process(os.getpid()).memory_info().rss
print(f"Memory (resident set size): {m / (1024 * 1024):.2f} MB.")
for t in end:
frame.loc(axis=0)[t0:t, :]
m = psutil.Process(os.getpid()).memory_info().rss
print(f"Memory (resident set size): {m / (1024 * 1024):.2f} MB.")
Issue Description
Accessing or slicing a DataFrame
with a MultiIndex
that has two levels, the first with Timestamp
entries and the second with string valued identifiers, shows an unexpected increase in memory usage.
One my machine, Apple M1, the initial memory usage (before the loc
access) is roughly 700MB. During the for-loop the memory footprint increases to up to 7000MB.
Expected Behavior
Maximum memory footprint should not be increasing with the number of loop iterations. The maximum memory footprint should not exceed (roughly) twice the memory required for the (initial) frame.
Installed Versions
NSTALLED VERSIONS
commit : 478d340
python : 3.9.16.final.0
python-bits : 64
OS : Darwin
OS-release : 22.4.0
Version : Darwin Kernel Version 22.4.0: Mon Mar 6 20:59:28 PST 2023; root:xnu-8796.101.5~3/RELEASE_ARM64_T6000
machine : arm64
processor : arm
byteorder : little
LC_ALL : None
LANG : None
LOCALE : en_GB.UTF-8
pandas : 2.0.0
numpy : 1.24.2
pytz : 2023.3
dateutil : 2.8.2
setuptools : 67.6.1
pip : 23.0.1
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : None
IPython : None
pandas_datareader: None
bs4 : None
bottleneck : None
brotli : None
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : None
numba : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : None
snappy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
zstandard : None
tzdata : 2023.3
qtpy : None
pyqt5 : None