Skip to content

PERF: high memory consumption for unstack #54373

@hkad98

Description

@hkad98

Pandas version checks

  • I have checked that this issue has not already been reported.

  • I have confirmed this issue exists on the latest version of pandas.

  • I have confirmed this issue exists on the main branch of pandas.

Reproducible Example

I use memory_profiler. Run mprof run file_name to measure memory consumption on each line of code.

import pandas as pd
import random
import string
from memory_profiler import profile


def random_string():
    return ''.join(random.choices(string.ascii_letters, k=7))


@profile
def main():
    records_count = 63531
    df = pd.DataFrame(
        {
            "A": random.choices([random_string() for _ in range(24)], k=records_count),
            "B": random.choices([random_string() for _ in range(14580)], k=records_count),
            "C": random.choices([random_string() for _ in range(9)], k=records_count),
            "D": random.choices([random_string() for _ in range(2311)], k=records_count),
            "E": random.choices([random_string() for _ in range(2)], k=records_count),
            "F": random.choices([random_string() for _ in range(280)], k=records_count),
            "M": random.sample(range(0, records_count), records_count)
        }
    )

    grouped_df = df.groupby(["A", "B", "C", "D", "E", "F"], dropna=False)[["M"]].sum(min_count=1, numeric_only=False)
    grouped_df.unstack("F")


if __name__ == "__main__":
    main()

Memory usage for unstack:

    27    264.1 MiB    171.8 MiB           1       grouped_df.unstack("F")

I tried to improve memory consumption with the following changes:

  • use category instead of string
  • use pivot_table instead of groupby + unstack
  • use reset_index + pivot instead of unstack

None of the things above worked.

I tried to turn on CoW, but it made it worse.

  28    390.6 MiB    306.1 MiB           1       grouped_df.unstack("F")

I am aware that CoW does not support unstack yet (#49473), but I would not expect that turning it on will make unstack worse.

Installed Versions

INSTALLED VERSIONS

commit : 0f43794
python : 3.10.8.final.0
python-bits : 64
OS : Darwin
OS-release : 22.5.0
Version : Darwin Kernel Version 22.5.0: Thu Jun 8 22:22:20 PDT 2023; root:xnu-8796.121.3~7/RELEASE_ARM64_T6000
machine : arm64
processor : arm
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : None.UTF-8

pandas : 2.0.3
numpy : 1.25.2
pytz : 2023.3
dateutil : 2.8.2
setuptools : 63.2.0
pip : 22.2.2
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

Prior Performance

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs InfoClarification about behavior needed to assess issuePerformanceMemory or execution speed performanceReshapingConcat, Merge/Join, Stack/Unstack, Explode

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions