Sub topic 4
pandas: the default for in-memory analysis
This chapter assumes you can load, filter, and group a dataset in pandas or SQL, and that you know basic Python types such as int, float, and str. Here you will learn how pandas works internally, why that makes it a good default, where it runs out of room, and which mistakes cost the most time.
The working model
pandas is a Python library for tabular data. Its main object is the DataFrame, a table of named columns that share a row index. Four properties explain most of its behavior.
- Eager execution. Every operation runs immediately and returns a new result.
df[df["revenue"] > 0]filters right away, so pandas cannot see the next step and cannot reorder or skip work. - In-memory.
read_csvandread_parquetload the data into RAM as a whole. If it does not fit, the process slows down, gets killed, or raisesMemoryError. - Single node, mostly single-threaded. Many operations run on one CPU core. NumPy handles some arithmetic quickly in compiled code. Group-bys, string methods, and
applywith a Python function usually do not use all cores. - Columns are typed arrays. Numeric columns are usually NumPy arrays. Strings are often stored as Python objects, which is costly. Recent versions add Arrow-backed and dedicated string dtypes that reduce this cost. Check which default your installed version uses.
The first code example in the topic spine shows this model. It loads two columns from Parquet and runs the group-by right away:
import pandas as pd
df = pd.read_parquet("sales.parquet", columns=["region", "revenue"])
result = df.groupby("region", as_index=False)["revenue"].sum()
print(result)Passing columns= here is a deliberate choice. pandas does not prune columns for you, so you must ask for only what you need.
Why it is the default
pandas is not the fastest of the four tools. It is the most widely known and the best connected to other tools.
- Ecosystem. scikit-learn, statsmodels, seaborn, Matplotlib, and most notebooks accept a DataFrame directly. Many tutorials, Stack Overflow answers, and internal scripts use it.
- Flexible, interactive API. You can inspect, mutate, and plot intermediate results one line at a time. This suits exploration.
- Rich built-in features. It has time-series resampling, rolling windows, pivot tables, multi-level indexes, and readers and writers for CSV, Excel, JSON, Parquet, and SQL.
- Low overhead for small data. Startup is a single import. For data in the thousands to low millions of rows, pandas often finishes before a more advanced engine has finished planning.
Where it runs out
Memory footprint
pandas needs more RAM than the file size suggests. A CSV holding mostly short strings can take several times its on-disk size once loaded as object columns. Intermediate results also take memory, because each step creates a new DataFrame and some operations copy the data.
A commonly cited rule of thumb is to keep 5 to 10 times the dataset size free as RAM. Newer versions need less, but treat the rule as a planning estimate and measure your own data. The Memory limits chapter covers this in detail.
No query optimization
Because execution is eager, pandas runs your steps in the order you wrote them. If you join two large tables and then filter, pandas performs the full join first. A lazy engine could move the filter before the join. In pandas, you do that optimization yourself.
Limited parallelism
One slow groupby().apply(python_function) on a large frame can take minutes on one core while the other cores sit idle. Vectorized operations (built-in column methods) are much faster than Python loops or apply.
Controlling memory in practice
You can often keep a dataset in pandas by choosing smaller types. The example below builds a million rows and compares memory before and after.
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 1_000_000
df = pd.DataFrame({
"region": rng.choice(["eu", "us", "apac", "latam"], size=n),
"revenue": rng.random(n) * 100,
"units": rng.integers(1, 50, size=n),
})
before = df.memory_usage(deep=True).sum() / 1e6
df["region"] = df["region"].astype("category")
df["units"] = df["units"].astype("int16")
df["revenue"] = df["revenue"].astype("float32")
after = df.memory_usage(deep=True).sum() / 1e6
print(f"before: {before:.1f} MB, after: {after:.1f} MB")Use deep=True. Without it, pandas counts only the pointer for each string and underreports memory for text columns.
Each conversion carries a trade-off:
| Change | Saves memory when | Risk |
|---|---|---|
| `category` for strings | Few distinct values repeat many times | Slower or awkward if almost every value is unique |
| `int16` or `int8` for integers | Values fit the smaller range | Values outside the range overflow or raise an error on conversion |
| `float32` for floats | Seven significant digits are enough | Rounding error in sums and money values |
| `usecols` or `columns=` at load | You need a few columns | None, apart from remembering to include join keys |
Reading in chunks
When a file is too big to load at once, chunksize lets you process it piece by piece. This works for aggregates you can combine, such as sums and counts.
from pathlib import Path
import pandas as pd
path = Path("sales.csv")
pd.DataFrame({
"region": ["eu", "us", "eu", "us"] * 250_000,
"revenue": range(1_000_000),
}).to_csv(path, index=False)
totals = None
for chunk in pd.read_csv(path, chunksize=200_000):
part = chunk.groupby("region")["revenue"].sum()
totals = part if totals is None else totals.add(part, fill_value=0)
print(totals)Chunking has limits. A median, a distinct count, or a join against another large table cannot be assembled from per-chunk answers this simply. If you start writing complex chunking code, that is a sign to try a tool built for larger-than-memory data.
Common errors
Chained assignment
This pattern may modify a temporary copy instead of your DataFrame:
df[df["revenue"] < 0]["revenue"] = 0Use a single .loc call so pandas knows exactly what to update:
df.loc[df["revenue"] < 0, "revenue"] = 0Recent pandas versions are moving toward copy-on-write, where a modified object never changes another object that shares its data. Under that rule the chained form never works. Write the .loc form regardless of version.
Row loops and `apply`
Looping with iterrows() or calling apply(axis=1) runs Python code once per row. A vectorized expression such as df["revenue"] * df["units"] runs in compiled code. On a million rows, the difference is often seconds against a fraction of a second.
Silent type changes
A column with missing values can change type. With classic NumPy-backed dtypes, an integer column that gains a missing value becomes float64. IDs then show up as 12345.0 and can lose precision above 2^53. Nullable dtypes such as Int64 keep integers as integers and mark missing values with pd.NA.
Reading everything, then selecting
pd.read_csv("big.csv") followed by df[["region", "revenue"]] pays the memory cost for every column. Pass usecols=["region", "revenue"] to the reader, or columns= for Parquet.
A quick fit check
The diagram below turns the discussion into a first-pass test for whether pandas is a reasonable choice.
Use the chart as a prompt for measurement, not as a verdict. Size estimates are rough, and "fast enough" depends on your deadline.
When pandas is the right call
Choose pandas when most of these hold:
- The data fits comfortably in memory, including intermediate copies.
- The work is exploratory, or the code feeds libraries that expect DataFrames.
- Your team already knows it, and the runtime is acceptable.
- The job is small or runs rarely, so engine startup and new dependencies cost more than they save.
Consider another tool when memory use becomes the main constraint, when a single job takes long enough to block people, or when the same transformation runs in production on large inputs. The next chapters describe the alternatives. pandas often stays in the workflow even then, as the final step where a small result is plotted, modeled, or inspected.
Exercise
A teammate wants to load a 2 GB CSV into pandas on a laptop with 16 GB of RAM. Most columns are text with repeated values such as country and product names. The job filters rows, then runs a group-by that sums revenue. Name two ways to lower memory use and one reason the job might still fail.
Show answer
Load only the needed columns with usecols (or switch to Parquet and pass columns=), and convert repeated-text columns to category dtype, or read in chunks and combine per-chunk sums. It can still fail because text stored as Python objects can use several times the file size once loaded, and intermediate copies from filtering or merging add to that. If the data holds many unique strings, category saves little. Check memory_usage(deep=True) on a sample to estimate the full cost first.