When do you reach for pandas DataFrame.from_records or DataFrame.from_dict(orient='index') instead of the plain DataFrame constructor?
answer
- alternate constructors for record-shaped data
- a field promoted to the index
- outer keys as rows, not columns
- columns only with orient='index'
- Decimal values from a SQL cursor
basics
~20 sUse from_records for tuples, structured arrays or cursor rows when you want a field as the index, fields excluded, Decimals coerced or only n rows read; use from_dict(orient='index') when a dict's keys are row IDs.
solid answer
~40 sThe plain constructor already handles a list of tuples with `columns=` and a dict of column lists, so the class methods earn their place through extra arguments. `DataFrame.from_records(data, index="order_id")` moves a named field into the index; `exclude=` drops fields; `coerce_float=True` turns `decimal.Decimal` values from a SQL result into `float64`; `nrows=` stops after n rows of an iterator. `DataFrame.from_dict(d, orient="index")` reads a dict keyed by row ID, such as `{"A1": {"qty": 2}}`, as rows, while `pd.DataFrame(d)` would make `A1` a column. Its `columns=` argument names the columns and is accepted only with `orient="index"`; with the default `orient="columns"` it raises `ValueError`. In pandas 3.0, `from_records` no longer accepts a DataFrame and raises `TypeError`; use `set_index` or `drop` instead.
code
python · 16 linesimport pandas as pd
cache = {"A1": {"qty": 2, "price": 9.5}, "A2": {"qty": 1, "price": 4.0}}
print(pd.DataFrame(cache))
print(pd.DataFrame.from_dict(cache, orient="index"))
rows = [("A1", 2, "ok"), ("A2", 1, "ok")]
by_id = pd.DataFrame.from_records(
rows, columns=["order_id", "qty", "audit"], index="order_id", exclude=["audit"]
)
print(by_id)
try:
pd.DataFrame.from_records(by_id)
except TypeError as exc:
print("TypeError:", exc)go deeper
Remember that from_dict(orient='index') turns a dict's keys into rows, while the plain constructor turns them into columns.
Explain what from_records adds over the constructor: index as a field name, exclude, coerce_float for Decimals and nrows for iterators.
Spot legacy calls that pass a DataFrame to from_records, which raise in pandas 3.0, and replace them with set_index or drop.
Weigh whether a shared loading helper should standardise on one constructor so that orientation mistakes surface in one reviewed place.
## Why pandas has alternate constructors The `pd.DataFrame(...)` constructor accepts dicts, lists of dicts, lists of tuples, NumPy arrays and more, so most code never needs anything else. pandas also ships two **class-method constructors**, `DataFrame.from_records` and `DataFrame.from_dict`, which accept narrower inputs and add arguments the general constructor lacks. Knowing those arguments is what an interviewer is testing: the methods are not faster or more correct, they are more expressive for particular input shapes. ## DataFrame.from_records `from_records` builds a frame from **row-shaped** data: a list or iterator of tuples, a list of dicts, or a NumPy **structured array** (an array whose dtype names its fields). Its signature is `from_records(data, index=None, exclude=None, columns=None, coerce_float=False, nrows=None)`. - `index=` takes **a field name** (or a list of names) and moves that field out of the columns into the row labels; it also accepts an array of labels. - `exclude=` lists fields to leave out, for example an internal audit column. - `columns=` names the fields of tuples, which carry no names of their own; for dicts or structured arrays it **selects and orders** fields, and a name the data lacks becomes an all-NA column. - `coerce_float=True` converts non-numeric, non-string objects such as `decimal.Decimal` to floating point, which the docstring describes as useful for SQL result sets; without it a Decimal column stays `object`. - `nrows=` reads only the first n rows when `data` is an iterator, which lets you peek at a database cursor without draining it. Compare `pd.DataFrame(rows, columns=["order_id", "price"])`: it produces the same frame from tuples, but it cannot promote a field to the index in the same call, cannot exclude fields and cannot stop after n rows. **A pandas 3.0 removal.** Passing an existing DataFrame to `from_records` was deprecated in pandas 2.1 and removed in 3.0, where it raises `TypeError` with a message pointing at `set_index` and `drop`. Legacy code that called `DataFrame.from_records(df, index="id")` to re-key a frame must switch to `df.set_index("id")`. ## DataFrame.from_dict `from_dict(data, orient="columns", dtype=None, columns=None)` reads a dict in one of three orientations: | `orient` | Dict keys become | Typical input | |---|---|---| | `"columns"` (default) | column labels | `{"qty": [2, 1], "price": [9.5, 4.0]}` | | `"index"` | row labels | `{"A1": {"qty": 2}, "A2": {"qty": 1}}` | | `"tight"` | read from named keys | `{"index": ..., "columns": ..., "data": ..., "index_names": ..., "column_names": ...}` | The `"index"` orientation is the reason to use it. A lookup table keyed by ID, such as a cache of orders mapping `"A1"` to a dict of fields, is naturally row-keyed. Passing it to the plain constructor gives the **transpose**: outer keys become columns and inner keys become rows. `from_dict(d, orient="index")` gives one row per ID. Two argument rules are worth stating precisely: 1. `columns=` **names** the columns and is valid only with `orient="index"`; with the default orientation, or with `"tight"`, it raises `ValueError` because the keys already supply the names. 2. `dtype=` is a **single** type forced on every column (from_dict hands it to the constructor); a per-column dict raises `TypeError`. The `"tight"` orientation is the inverse of `to_dict(orient="tight")`: it rebuilds a frame including the names of its index and column levels, which the lesson on interop with other formats covers. ## Picking one in practice 1. **API records as a list of dicts**: the plain constructor, or `from_records` when one field should become the index straight away. 2. **Rows from a database cursor**: `from_records(cursor_rows, columns=names, coerce_float=True)`, adding `nrows=` to sample an iterator. 3. **A dict keyed by row ID**: `from_dict(d, orient="index")`, with `columns=` when the values are lists rather than dicts. 4. **Re-keying an existing frame**: `set_index`, never `from_records`, which raises in pandas 3.0. ## Mistakes interviewers listen for - Expecting `pd.DataFrame(d)` on a dict keyed by ID to give one row per ID; it gives one **column** per ID, and mixed fields in one column upcast together (an integer `qty` beside a float `price` becomes `float64`). - Passing `columns=` to `from_dict` without `orient="index"` and being surprised by the `ValueError`. - Treating `from_records(index=...)` as a list of labels only, when its common use is a **field name**. - Assuming `dtype=` on `from_dict` can type columns individually; it applies one dtype to all of them. - Porting 2.x code that re-keyed a frame through `from_records(df, ...)` without replacing it with `set_index`. Each method returns a new DataFrame with a default `RangeIndex` unless `index=` or `orient="index"` supplies row labels, so `df.shape` and `df.head()` remain the quickest check that the orientation came out the way you meant.
- Why does pd.DataFrame(cache) show qty as 2.0 when every qty in the cache is an integer?The plain constructor makes each outer key a column, so the `A1` column holds both `qty` (2) and `price` (9.5). One column has one dtype, so the integer is upcast to `float64`. With `from_dict(cache, orient="index")`, `qty` and `price` are separate columns and `qty` stays `int64`.
- What does from_dict(d, orient='index') produce when the values are lists instead of dicts?Each key becomes a row label and the list positions become columns labelled 0, 1, 2 and so on, because a list carries no field names. Pass `columns=[...]` to name them; that argument is accepted only with `orient="index"`.
- pd.DataFrame on a dict of dicts makes the outer keys the rows
- from_dict accepts columns= with its default orientation
- from_records still accepts a DataFrame in pandas 3.0
- from_records index= must be a list of labels, never a field name
- from_dict dtype= takes a per-column mapping of dtypes
Assumes pandas 3.0: DataFrame.from_records accepted a DataFrame in 2.x (deprecated since 2.1); in 3.0 it raises TypeError.