Sub topic 11
Metadata (meta) and how Dask infers output types
This chapter assumes you know how to build a lazy Dask DataFrame and call map_partitions (covered in earlier chapters). It also assumes you are comfortable with pandas dtypes such as int64, float64, object, and category. Here you will learn what meta is, how Dask infers it, when inference fails, and how to supply meta yourself.
What meta is
A Dask DataFrame is lazy. When you write ddf["fare"] * 2, Dask has not touched any data yet. It still has to tell you that the result is a Series named fare with dtype float64, and it has to know this before any partition is loaded.
The answer is meta. It is a small, empty pandas object that has the same column names, dtypes, and index type as the real result would have. Every Dask DataFrame and Series carries one. You can inspect it:
import pandas as pd
import dask.dataframe as dd
pdf = pd.DataFrame({
"zone": ["a", "b", "a", "b"],
"fare": [10.0, 20.0, 30.0, 40.0],
})
ddf = dd.from_pandas(pdf, npartitions=2)
print(ddf.dtypes) # read from meta, no data is computed
print(ddf._meta) # an empty pandas DataFrame with the same columns
print(len(ddf._meta)) # 0
print(ddf["fare"].dtype) # float64ddf._meta is a private attribute, so use it for exploring and debugging rather than in library code. The public attributes dtypes, columns, and dtype are all answered from meta.
Dask uses meta for three jobs:
- It answers questions like
ddf.columnsandddf.dtypesinstantly. - It checks that later operations make sense. For example, selecting a column that is not in meta raises
KeyErrorwhile you build the graph, before any work runs. - It tells Dask what type of object each task returns, such as DataFrame, Series, or scalar, so it can pick the right code path for the next operation.
How Dask infers meta
Built-in operations such as +, groupby().mean(), and assign know how to compute their own output meta. You never see this step.
Custom code is different. When you call map_partitions(func) without meta, Dask cannot know what func returns. It guesses by calling func on a small fake DataFrame built from the input's meta. This fake frame is called the non-empty meta, and you can see it as ddf._meta_nonempty. It contains a couple of rows of placeholder values that match each column's dtype: some number for numeric columns, a short string such as "foo" for string columns, and so on.
Dask then takes whatever func returned on that fake frame, empties it, and uses the result as the output meta.
A function you have already seen shows this in action:
def add_fare_cents(part):
# part is an ordinary pandas DataFrame
return part.assign(fare_cents=(part["fare"] * 100).astype("int64"))
ddf2 = ddf.map_partitions(add_fare_cents)
print(ddf2.dtypes) # fare_cents is int64, learned from the fake run
print(ddf2.compute())Inference worked here because the function behaves well on arbitrary numbers.
When inference goes wrong
The fake-data run is a guess, so it can fail or mislead in three ways.
The function fails on fake values
The fake frame holds placeholder values, not your real data. A function that parses strings, looks values up in a dictionary, or divides by a column can raise on those placeholders even though it works on every real row. Dask then raises an error that starts with Metadata inference failed, and the message suggests passing meta=.
def parse_zone_code(part):
# Works on real zones such as "a", but not on the fake string "foo"
codes = {"a": 1, "b": 2}
return part.assign(zone_code=part["zone"].map(lambda z: codes[z]))Because the placeholder string is not a key in codes, parse_zone_code raises KeyError during inference. Passing meta skips the fake run entirely, which fixes the error.
The function has side effects
Inference calls your function once on fake data at graph-build time, in addition to the real calls. A print, a log line, or a write to a file or database will fire an extra time, before you call compute(). Supplying meta prevents that extra call.
The guess is wrong
Inference can return the wrong dtype when the output depends on the data. A column that is int64 on the fake rows may contain missing values in real data and become float64. A function that returns a different column set depending on the values it sees will also produce meta that does not match the real partitions.
Supplying meta yourself
You tell Dask the output type with the meta= argument. It accepts several forms:
| Output is | Form of `meta` | Example |
|---|---|---|
| DataFrame | An empty pandas DataFrame | `ddf._meta.assign(x=pd.Series(dtype="int64"))` |
| DataFrame | A dict of column names to dtypes | `{"zone": "object", "fare": "float64"}` |
| DataFrame | A list of `(name, dtype)` tuples | `[("zone", "object"), ("fare", "float64")]` |
| Series | A `(name, dtype)` tuple | `("zone_upper", "object")` |
| Scalar | A value of the right type | `0.0` |
The dict and tuple-list forms define the columns in the order you write them, so list them in the order your function returns them. For an add-a-column function, building from the input's meta keeps all existing columns and dtypes correct:
meta = ddf._meta.assign(fare_cents=pd.Series(dtype="int64"))
ddf3 = ddf.map_partitions(add_fare_cents, meta=meta)
print(ddf3.dtypes)
print(ddf3.compute())For a function that returns a Series, give the name and dtype as a tuple. Reading the dtype from the input avoids hardcoding whether strings are object or a newer string dtype in your environment:
def zone_upper(part):
return part["zone"].str.upper()
upper = ddf.map_partitions(zone_upper, meta=("zone_upper", ddf["zone"].dtype))
print(upper.compute())Methods that take a Python function per row or per group, such as apply(..., axis=1) and groupby().apply(), also need meta. They emit a warning when it is missing, and inference can be slow or wrong for them:
doubled = ddf.apply(lambda row: row["fare"] * 2, axis=1, meta=("fare_x2", "float64"))
print(doubled.compute())Meta is a promise, not a check
Dask does not compare your meta with the real output. If the two disagree, the graph builds without any error and the mismatch surfaces later, often far from the cause.
def fare_as_float(part):
return part["fare"] * 1.5 # actually returns float64
wrong = ddf.map_partitions(fare_as_float, meta=("fare", "int64"))
print(wrong.dtype) # int64, because Dask trusts your meta
print(wrong.compute().dtype) # float64, what the data really isBetween those two lines, Dask believed the result was an integer. Operations that depend on dtype, such as merges, writing Parquet with a fixed schema, or astype decisions, may then fail or behave differently across partitions.
When you see a symptom like dtypes reporting one type and compute() returning another, or a Parquet write complaining about schema mismatches between partitions, check meta first. A quick comparison helps:
real = wrong.compute()
print(wrong._meta.dtype, real.dtype)Dask's assert_eq helper from dask.dataframe.utils goes further. It computes the result and checks that meta and the real output agree on column names and dtypes. It is useful in tests.
Practical guidelines
- Pass
metawhenever you callmap_partitions,apply, ormapwith your own function. It is cheap to write and removes a class of surprises. - Build DataFrame meta from
ddf._metaand change only what your function changes. This keeps all other columns correct. - Be precise with dtypes.
int64versusfloat64,objectversus a string dtype, andcategorywith its categories can all matter downstream. - Watch for missing values. If a column can contain nulls after your function, an integer meta is wrong. Use a float dtype or a nullable one such as
"Int64". - Do not treat an inference failure as a bug in Dask. It tells you that your function does not accept arbitrary placeholder data, which is a signal to provide meta.
Exercise
You write ddf.map_partitions(label_rows) where label_rows looks up each zone value in a dictionary and raises KeyError for any key not in the dictionary. Dask reports "Metadata inference failed". Why does this happen even though every real zone is in the dictionary, and how do you fix it? Write the fix assuming label_rows adds an object column called label.
Show answer
Without meta, Dask calls label_rows on a fake frame whose zone column holds placeholder strings such as "foo". Those are not keys in the dictionary, so the function raises and inference fails, even though real data would work. Fix it by passing meta so the fake run is skipped: ddf.map_partitions(label_rows, meta=ddf._meta.assign(label=pd.Series(dtype="object"))).