Sub topic 10
Building a DataFrame without appending in a loop
This chapter assumes you can write Python loops and functions, and that you know how to select, filter, and concatenate pandas DataFrames. It also assumes you have read the earlier chapters on timing code with perf_counter and on checking that an optimized version gives the same result. The chapter explains why growing a DataFrame one piece at a time is slow, then shows the replacements and the edge cases they bring.
The pattern to avoid
A common way to collect results is to start with an empty DataFrame and add to it inside a loop:
result = pd.DataFrame()
for part in parts:
result = pd.concat([result, part])This looks harmless, and it works. It is slow because a DataFrame is not a growable container. Its columns are stored as NumPy arrays of fixed length. Each pd.concat call allocates new arrays big enough for everything so far, copies the old data into them, and then copies the new piece in. The old frame is thrown away.
The cost adds up. Suppose you have 2,000 pieces of 50 rows each. The final frame has 100,000 rows. The loop copies 50 rows on the first pass, 100 on the second, 150 on the third, and so on. The total is 50 × (2,000 × 2,001 / 2), or about 100 million row copies. Building the result once copies 100,000 rows. The work grows with the square of the number of pieces, so doubling the pieces roughly quadruples the time.
Measuring the difference
Following the "measure first" rule from earlier chapters, time both versions on the same data. This script builds 2,000 small frames and times both approaches.
import numpy as np
import pandas as pd
from time import perf_counter
rng = np.random.default_rng(0)
parts = [
pd.DataFrame({"id": np.arange(i * 50, (i + 1) * 50), "value": rng.random(50)})
for i in range(2_000)
]
start = perf_counter()
slow = pd.DataFrame()
for part in parts:
slow = pd.concat([slow, part], ignore_index=True)
print(f"concat in loop: {perf_counter() - start:.3f}s")
start = perf_counter()
fast = pd.concat(parts, ignore_index=True)
print(f"single concat: {perf_counter() - start:.3f}s")
pd.testing.assert_frame_equal(slow, fast, check_dtype=False)
print(fast.shape)The single concat is typically tens to hundreds of times faster here, and the gap widens as you add pieces. Your numbers will differ by machine and pandas version, so run it yourself.
The last check follows the verification habit from the earlier chapter. It passes only if both frames hold the same values in the same order. The call uses check_dtype=False because starting from an empty frame can change column dtypes in some pandas versions. After you have confirmed the values match, you should still compare slow.dtypes and fast.dtypes yourself, because dtype changes can matter downstream.
Fix 1: collect pieces in a list, concatenate once
When each piece is already a DataFrame, for example one per file, per API page, or per group, put the pieces in a list and call pd.concat once.
import pandas as pd
# Slow: copies the growing frame on every iteration
result = pd.DataFrame()
for part in parts:
result = pd.concat([result, part])
# Fast: one concatenation at the end
result = pd.concat(parts, ignore_index=True)Appending to a Python list is cheap. A list stores references to the frames, so nothing is copied. pd.concat then sizes the output once and fills it.
A few details are worth knowing:
ignore_index=Truegives the result a fresh index from 0 to n−1. Without it, the result keeps each piece's own index, so you can end up with duplicate labels. Duplicate labels make.loclookups return several rows and can raise errors inreindexandmerge.pd.concat([])raisesValueError: No objects to concatenate. If your list may be empty, handle that case explicitly (see the edge cases below).pd.concataccepts any iterable, including a generator, and consumes it once.
Fix 2: collect rows as dicts or tuples
Often each piece is a single row, not a DataFrame. In that case, do not build a one-row DataFrame per iteration. Collect plain Python dicts or tuples and construct the DataFrame once.
import pandas as pd
rows = []
for i in range(100_000):
rows.append(
{"order_id": i, "amount": float(i % 97), "region": "N" if i % 2 else "S"}
)
orders = pd.DataFrame(rows)
print(orders.dtypes)pd.DataFrame(list_of_dicts) reads the keys as column names. Keys missing from some dicts become NaN. For long lists of fixed-shape records, tuples with an explicit columns argument are a little faster and fail loudly if a row has the wrong length:
import pandas as pd
records = [(i, float(i % 97), "N" if i % 2 else "S") for i in range(100_000)]
orders = pd.DataFrame(records, columns=["order_id", "amount", "region"])Another slow pattern looks like in-place growth:
import pandas as pd
df = pd.DataFrame(columns=["order_id", "amount"])
for i in range(5_000):
df.loc[len(df)] = [i, float(i)] # slow: enlarges the frame row by rowSetting a row with .loc on a new label enlarges the frame, and this too reallocates arrays on each call. It also leaves every column as object dtype, because the frame started empty with no declared types. Replace it with the list approach. The removed DataFrame.append method (gone since pandas 2.0) had the same cost problem as the concat loop.
Fix 3: preallocate arrays when the size is known
If you know the number of rows in advance, you can fill NumPy arrays and wrap them in a DataFrame at the end. This suits loops where each value depends on the previous one, so you cannot vectorize them.
import numpy as np
import pandas as pd
rng = np.random.default_rng(1)
n = 100_000
steps = rng.normal(0, 0.5, n)
prices = np.empty(n, dtype="float64")
level = 100.0
for i in range(n):
level = max(1.0, level + steps[i]) # depends on the previous value
prices[i] = level
path = pd.DataFrame({"step": np.arange(n), "price": prices})
print(path.tail(3))The loop still runs in Python, but each iteration writes into an existing array and allocates nothing. The DataFrame is created once. Before reaching for this, check whether the loop is really order-dependent. Many "running" calculations have vectorized forms such as cumsum, cummax, shift, and rolling.
If you do not know n in advance, use a Python list and convert at the end with np.array(values) or pd.Series(values). Lists grow efficiently, because Python over-allocates capacity. NumPy arrays do not.
Fix 4: stream many files into one concat
Reading many files is the most common reason to build a frame in pieces. Use a generator expression so pieces are produced as needed, and call pd.concat once. This example creates its own small CSV files so it runs as written.
import tempfile
from pathlib import Path
import numpy as np
import pandas as pd
rng = np.random.default_rng(2)
with tempfile.TemporaryDirectory() as tmp:
folder = Path(tmp)
for day in range(1, 6):
pd.DataFrame(
{"amount": rng.random(1_000), "qty": rng.integers(1, 10, 1_000)}
).to_csv(folder / f"day_{day}.csv", index=False)
paths = sorted(folder.glob("*.csv"))
if not paths:
raise FileNotFoundError("no CSV files found")
frames = (pd.read_csv(p).assign(source=p.name) for p in paths)
combined = pd.concat(frames, ignore_index=True)
print(combined.shape)
print(combined["source"].value_counts().sort_index())Note assign(source=p.name). It records which file each row came from, which is hard to rebuild afterward. The sorted call makes the row order reproducible, because glob returns paths in an arbitrary, platform-dependent order.
The explicit empty check matters. pd.concat on an empty iterable raises ValueError, and that message does not tell you that the real problem is a wrong path or pattern.
Edge cases when concatenating
Concatenating once is faster, but it does not remove the need to think about types and shapes.
- Mismatched columns. By default
pd.concattakes the union of columns and fills gaps withNaN. Integer columns with gaps becomefloat64, becauseNaNis a float. Passjoin="inner"to keep only shared columns, or fix the inputs so they match. - Category columns. If pieces have
categorydtype with different category sets, the result falls back toobject, which uses much more memory. Convert the column tocategoryafter the concat, or build a sharedCategoricalDtypeand apply it to every piece first. - Empty pieces. Recent pandas versions warn when empty or all-NA entries take part in dtype resolution, because that behavior will change. Filter them out with
[p for p in parts if not p.empty]before concatenating. - Memory peak.
pd.concatneeds the pieces and the result in memory at once, so the peak is about twice the final size. If that is too much, reduce each piece first (select columns, downcast dtypes, or aggregate), or process in chunks as described in the final chapter.
Choosing a pattern
| Situation | Pattern | Why |
|---|---|---|
| Pieces are DataFrames (files, groups, pages) | List or generator, then one `pd.concat` | Each row copied once |
| Pieces are single records | List of dicts or tuples, then `pd.DataFrame` | No per-row DataFrame overhead |
| Size known, values depend on earlier values | Preallocated NumPy arrays, then `pd.DataFrame` | No reallocation in the loop |
| Values can be computed from whole columns | Vectorized expression | No Python loop at all |
| Results only feed an aggregate | Aggregate each piece, combine summaries | Much less data to concatenate |
Summary of rules
- Never grow a DataFrame inside a loop with
pd.concat,.loc[len(df)], or the removedappend. - Collect pieces in a list, then build the frame once.
- Use
ignore_index=Trueunless the original index carries meaning. - Guard against an empty list before calling
pd.concat. - After combining, check dtypes, not just values.
Exercise
A script reads 500 CSV files, each with about 2,000 rows, and builds one DataFrame with df = pd.concat([df, pd.read_csv(p)]) inside a loop that starts from df = pd.DataFrame(). Rewrite the loop so it builds the frame in one concat, keeps a column named source holding each file's name, and fails with a clear message when no files match. Then say how you would check that the new frame matches the old one.
Show answer
Build a sorted list of paths with paths = sorted(Path("data").glob("*.csv")). If paths is empty, raise a FileNotFoundError with a message naming the folder and pattern. Then run frames = (pd.read_csv(p).assign(source=p.name) for p in paths) and df = pd.concat(frames, ignore_index=True). The loop version copied the growing frame 500 times, which is about 125,000 times the per-file row count in total row copies (2,000 × 500 × 501 / 2 = 250,500,000 rows, against 1,000,000 for the single concat). To check equality, build the old result with ignore_index=True as well (or call reset_index(drop=True) on it), then run pd.testing.assert_frame_equal(old, new, check_dtype=False). After that, compare old.dtypes and new.dtypes by eye, since starting from an empty frame can alter dtypes in some pandas versions.