Sub topic 10
Building a DataFrame without appending in a loop
This chapter assumes you can write Python loops and list comprehensions and that you know how to build a DataFrame and call pd.concat. It builds on the earlier chapters on timing and on why row-wise code is slow.
Why appending in a loop is slow
A DataFrame stores its columns in contiguous blocks of memory. Pandas cannot grow those blocks in place. Each pd.concat([result, part]) allocates new memory and copies every row collected so far, plus the new part.
With n parts, the loop copies about 1 + 2 + ... + n parts' worth of data. The cost grows with the square of n, not linearly. The code looks harmless at 10 parts and becomes the bottleneck at 5,000.
The same cost applies to other ways of growing a frame one row at a time:
df.loc[len(df)] = rowenlarges the frame and copies it on every call.DataFrame.appenddid the same hidden copying. Pandas 2.0 removed it, so old code that uses it fails with anAttributeError.
Collect first, concatenate once
Keep the pieces in a plain Python list. Lists append in constant time. Call pd.concat once after the loop.
import pandas as pd
from time import perf_counter
parts = [
pd.DataFrame({"id": range(i * 100, i * 100 + 100), "value": range(100)})
for i in range(1_000)
]
start = perf_counter()
slow = parts[0]
for part in parts[1:]:
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)The final line applies the habit from the verification chapter. It confirms that both versions return the same frame. Pass ignore_index=True so the result gets a fresh 0..n-1 index instead of repeating each part's own index.
Build from records, not from rows
Sometimes there are no ready-made DataFrames to join. You are producing one row at a time, for example while parsing text or calling an API. In that case, append plain dictionaries to a list and build the DataFrame once.
import pandas as pd
records = []
for order_id in range(10_000):
records.append({"order_id": order_id, "amount": order_id * 0.5})
orders = pd.DataFrame(records)
print(orders.dtypes)Python dictionaries are cheap to create. The DataFrame constructor then infers each column's dtype from the whole list in one pass.
A related option is a dictionary of lists, such as pd.DataFrame({"order_id": ids, "amount": amounts}). It is slightly faster, because pandas does not need to pivot the records into columns.
Common errors
- Starting from an empty frame. Recent pandas versions warn about concatenating empty entries, because the dtype of the result may change. Collecting into a list avoids the empty seed.
- Concatenating an empty list.
pd.concat([])raisesValueError: No objects to concatenate. Checkif parts:first. - Forgetting the index. Without
ignore_index=True, the result has duplicate index labels. Later.loclookups then return several rows instead of one. - Mixed dtypes across parts. If one part has an integer column and another has missing values or strings, the combined column may become
float64orobject. Checkfast.dtypesafter concatenating.
When the pieces come from files
The same rule applies when you read many files. Read each file into a list element, usually with a list comprehension, and call pd.concat once:
from pathlib import Path
import pandas as pd
frames = [pd.read_csv(path) for path in Path("data").glob("*.csv")]
combined = pd.concat(frames, ignore_index=True) if frames else pd.DataFrame()Exercise
A loop reads 2,000 small API responses. Each iteration runs df = pd.concat([df, pd.DataFrame([row])]). Runtime grows much faster than the number of responses. Why, and how would you rewrite it?
Show answer
Each concat copies every row accumulated so far, so total copying grows with the square of the number of responses. Append each row dictionary to a list inside the loop, then call pd.DataFrame(rows) once after the loop. Check with pd.testing.assert_frame_equal against the old result, using ignore_index=True or reset_index(drop=True) so the indexes match.