Pandas Memory Optimization: Choose Smaller Types Without Losing Values

Measure each column, preserve exact prices, bound the error on sensor readings, and aggregate a CSV in chunks with pandas.

A price column can pass a memory test and fail a reconciliation. Two prices a cent apart become identical in float32 at a million dollars. Start by deciding what each column must preserve. Then measure how much memory its representation costs.

Understanding Pandas Data Types

Read these prices as text so that a binary float never stands between the source amount and the accounting calculation. This example accepts finite, nonnegative amounts in a currency with two decimal places, with no fractional cents. A feed that includes refunds, multiple currencies or fractional cents needs its own contract.

Python
from decimal import Decimal
from io import StringIO
import pandas as pd

csv = StringIO("item,price\na,1000000.01\nb,1000000.02\n")
orders = pd.read_csv(csv, dtype={"price": "string"})
prices = orders["price"].map(Decimal)
assert all(p.is_finite() and p >= 0 and p == p.quantize(Decimal("0.01"))
           for p in prices)
assert prices.iloc[1] - prices.iloc[0] == Decimal("0.01")

approx = orders["price"].astype("float32")
assert approx.iloc[0] == approx.iloc[1]

orders["price_cents"] = pd.Series([int(p * 100) for p in prices], dtype="int64")
assert orders["price_cents"].tolist() == [100000001, 100000002]

Integer minor units are convenient when the scale is fixed. Check the representable range for the largest total as well as the largest individual price. Keep the currency alongside the amount when a table mixes currencies. Python’s decimal documentation explains what happens if a float has already rounded the input. Python decimal arithmetic

Automatic Memory Optimization

For an approximate measurement, choose the allowed error in the measurement’s own units. These readings tolerate an absolute difference of 0.001 degrees. Null positions must also survive. This example checks the values after casting back to the original precision.

Python
import numpy as np
import pandas as pd

readings = pd.Series([1.25, 2.5, 31.123456, np.nan], dtype="float64")
candidate = readings.astype("float32")
np.testing.assert_allclose(readings, candidate.astype("float64"),
                           rtol=0, atol=0.001, equal_nan=True)
assert pd.to_numeric(pd.Series([1.25, 2.5]), downcast="float").dtype == "float32"

The smallest floating type chosen by to_numeric(..., downcast="float") is float32. The function has no knowledge of your error budget. Apply any conversion by column name after validating its contract. For counts, check both the integer range and the treatment of missing values. For identifiers such as "007", preserve the text. pandas numeric conversion

Measuring Your Own Results

memory_usage(deep=True) estimates the memory used by the current frame, including its index. A category stores a dictionary of labels plus codes. It can save space for repeated labels. A column of nearly unique strings may grow instead. Compare on the same rows and check equality after restoring the original dtype.

Python
import pandas as pd

sample = pd.DataFrame({"region": ["east", "west"] * 1000, "count": [1, 300] * 1000})
before = sample.memory_usage(index=True, deep=True)
smaller = sample.assign(region=sample["region"].astype("category"),
                        count=pd.to_numeric(sample["count"], downcast="integer"))
pd.testing.assert_frame_equal(smaller.astype(sample.dtypes.to_dict()), sample)
print(pd.concat([before, smaller.memory_usage(index=True, deep=True)],
                axis=1, keys=["before_bytes", "after_bytes"]))

Keep peak process memory separate from final column size. During conversion the old and new arrays can coexist. Time a representative filter or group-by, then check totals and null counts on the result. The smallest final frame can still be the slowest one to build. pandas memory usage

Vectorization Over Iteration

For a row-wise expression such as quantity times unit price, calculate the whole column. This sales fixture checks the line totals in integer cents and groups them once. A vectorized expression still produces an output array, which counts toward peak memory. Bound both the multiplication and its aggregate to fit the chosen integer type.

Python
import pandas as pd

lines = pd.DataFrame({"store": ["west", "east", "west"],
                      "units": [2, 3, 1], "unit_cents": [125, 50, 75]})
lines["line_cents"] = lines["units"] * lines["unit_cents"]
assert lines["line_cents"].tolist() == [250, 150, 75]
assert lines.groupby("store")["line_cents"].sum().to_dict() == {"east": 150, "west": 325}

Indexing for Fast Lookups

Before adding an index for repeated lookups, check for duplicate keys. In this example, west has two rows. Treating the store as a unique identifier would change what a lookup returns. If the consumer needs one row per store, aggregate first and verify the number of rows. If it needs individual sales, keep a transaction identifier. Include index construction time and memory in your comparison.

Chunk Processing for Huge Files

If the task only needs a total by region, carry those totals across chunks. Summing each region independently inside a chunk and printing the last chunk would discard earlier sales. The two-row chunk below deliberately splits the east region across the boundary. Use a chunk size that fits your own machine.

Python
from collections import Counter
from io import StringIO
import pandas as pd

sales = StringIO("region,cents\neast,100\nwest,250\neast,25\n")
totals = Counter()
for chunk in pd.read_csv(sales, chunksize=2, dtype={"cents": "int64"}):
    totals.update(chunk.groupby("region")["cents"].sum().to_dict())
assert totals == {"east": 125, "west": 250}

A mean needs both a sum and a count. A median requires a different algorithm. If a large join is the constraint, run it on representative keys and measure peak memory separately. Our pandas, Polars and DuckDB comparison includes an equivalent aggregation for all three engines.

Correction, November 25, 2026. An earlier version recommended float32 for prices and gave universal speed and memory savings. The price counterexample, error check and chunk totals above replace those claims.

Share this article

X Facebook LinkedIn Reddit Telegram

Your notes on this article

Your name or initials, note and date stay in this browser profile. Anyone using the profile can read them. Delete a note below or clear this site’s browser data. To reach the editors, report a correction.

No notes saved here