Sub topic 4
Data types and schemas
Every Arrow column has a data type, and every table has a schema that lists those types. This chapter covers the built-in types, how pyarrow infers and casts them, and how a schema describes a table. It assumes you have read the chapters on columnar layout and on buffers, validity bitmaps and offsets. It also assumes you can run Python with pyarrow installed.
Why the type matters
An Arrow type is more than a label. It decides which buffers an array has and how to read them. An int32 array has a validity bitmap and a data buffer holding 4 bytes per value. A string array has a validity bitmap, an offsets buffer and a data buffer of UTF-8 bytes. A reader in another language that knows only the type can find every value in the memory, which is why a shared format works.
Types are also part of the contract between tools. If one tool writes int32 and another expects int64, the data must be cast, and a cast copies. Choosing types deliberately avoids those copies.
The main type families
Arrow types fall into a few families. The diagram shows the grouping, and the table lists the types you will meet most often.
| Type | pyarrow constructor | Notes |
|---|---|---|
| Signed integers | `pa.int8()` to `pa.int64()` | Unsigned versions are `pa.uint8()` to `pa.uint64()`. |
| Floating point | `pa.float32()`, `pa.float64()` | Printed as `float` and `double`. |
| Boolean | `pa.bool_()` | Stored as one bit per value, not one byte. |
| Text | `pa.string()`, `pa.large_string()` | UTF-8. The large version uses 64-bit offsets. |
| Bytes | `pa.binary()`, `pa.large_binary()` | Same layout as text without the UTF-8 guarantee. |
| Decimal | `pa.decimal128(precision, scale)` | Exact numbers. Precision is at most 38. |
| Timestamp | `pa.timestamp(unit, tz=None)` | Unit is `s`, `ms`, `us` or `ns`. |
| Date and time | `pa.date32()`, `pa.time64("us")` | `date32` counts days since 1970-01-01. |
| List | `pa.list_(pa.int32())` | A variable-length sequence of one value type. |
| Struct | `pa.struct([...])` | Named child fields, like a record. |
| Dictionary | `pa.dictionary(pa.int32(), pa.string())` | Small integer indices into a list of distinct values. |
| Null | `pa.null()` | A column where every value is null. |
Fixed-width and variable-width
Fixed-width types such as int64 need only a data buffer, because value i sits at byte i * width. Variable-width types such as string need offsets, because values differ in length. The cost of a string column is therefore the offsets plus the bytes.
The large_* variants exist because 32-bit offsets cap a single array at about 2 GiB of character data. Use large_string only when you need more than that in one array. Otherwise it doubles the offsets for nothing, and some tools handle it less well than string.
Temporal types carry a unit
A timestamp is a 64-bit integer plus a unit and an optional time zone. The same integer means different instants under different units, so the unit is part of the type:
pa.timestamp("ms")andpa.timestamp("us")are different types.- A timestamp with
tz="UTC"holds UTC instants. One without a zone is a "naive" local time and does not name a single instant. - pandas uses nanosecond timestamps by default. Converting from pandas can produce
timestamp[ns]columns that some other tools do not accept.
Type inference
When you build an array from Python values without giving a type, pyarrow infers one.
import pyarrow as pa
print(pa.array([1, 2, 3]).type)
print(pa.array([1.5, 2]).type)
print(pa.array(["x", None]).type)
print(pa.array([None, None]).type)
print(pa.array([1, 2], type=pa.int8()).type)This prints int64, double, string, null and int8. Three rules explain the output:
- Python integers become
int64, and floats becomedouble. - Mixed integers and floats widen to
double. Mixed numbers and text raisepa.ArrowInvalid. - A list of only
Nonehas no values to inspect, so the type isnull. If a later batch of the same column holds real values, the types will not match. Passtype=whenever a column could be all null.
Inference is convenient in notebooks but fragile in pipelines. The type of a column then depends on whichever rows arrived first. Declare types explicitly at the edges of your code.
Schemas
A schema is an ordered list of fields. A field has a name, a type, a nullable flag and optional metadata. The schema carries no data. Two tables with the same schema can be combined, written to the same file or passed through the same function.
This example builds a schema and a table that follows it.
import pyarrow as pa
schema = pa.schema([
("id", pa.int64()),
("name", pa.string()),
])
table = pa.table({"id": [1, 2, 3], "name": ["a", None, "c"]}, schema=schema)
print(table.schema)
print(table.num_rows)The output lists id: int64 and name: string, then 3. Passing schema= makes pyarrow convert each column to the declared type instead of inferring one. If a value cannot be converted, you get an error at construction time rather than a surprise later.
Fields, nullability and metadata
For more control, build pa.field objects and attach schema-level metadata:
import pyarrow as pa
schema = pa.schema(
[
pa.field("id", pa.int64(), nullable=False),
pa.field("name", pa.string()),
pa.field("created", pa.timestamp("ms", tz="UTC")),
],
metadata={"source": "users export"},
)
print(schema)
print(schema.field("id").nullable)
print(schema.names)
print(schema.metadata)The last line prints {b'source': b'users export'}. Metadata keys and values are stored as bytes, and Arrow does not interpret them. Other libraries use them for their own purposes. For example, pandas stores a description of the DataFrame index there.
The nullable flag declares that a column has no nulls. It is a promise that readers may rely on, and it is not a guarantee that pyarrow checks at every step. Treat it as documentation that other tools may act on. Do not use it as input validation.
Comparing schemas
schema.equals(other) compares names, types and nullability. Metadata is ignored by default, and check_metadata=True includes it. A common failure is two files that look the same but differ in one field, such as int32 versus int64, or string versus large_string. Compare schemas before concatenating tables, and use table.cast(target_schema) to bring one table in line with the other.
Casting between types
Array.cast and Table.cast convert values to another type. Casts are safe by default, which means pyarrow raises an error instead of losing information.
import pyarrow as pa
arr = pa.array([1, 300])
print(arr.cast(pa.int32()))
try:
arr.cast(pa.int8())
except pa.ArrowInvalid as exc:
print("cast failed:", exc)
print(arr.cast(pa.int8(), safe=False))The first cast succeeds. The second raises because 300 does not fit in int8. The third passes safe=False, so the value wraps around to 44. Use safe=False only when you have checked the data, because wrapped values are silently wrong.
Casting always allocates a new array, because the bytes for each value change. This differs from sharing memory, which later chapters cover. A cast between int32 and int64 is never zero-copy. Casting from string to large_string rewrites the offsets buffer.
Dictionary and nested types
A dictionary type stores each distinct value once and keeps a small integer index for every row. It suits columns with few distinct values, such as country codes or status names.
import pyarrow as pa
names = pa.array(["red", "green", "red", "red"])
encoded = names.dictionary_encode()
print(encoded.type)
print(encoded.indices)
print(encoded.dictionary)The type prints as dictionary<values=string, indices=int32, ordered=0>. The indices are 0, 1, 0, 0 and the dictionary is ["red", "green"]. The saving is real only when values repeat often. A column of unique strings gets larger.
Nested types describe structured values while keeping the columnar layout. Each child is itself a column.
import pyarrow as pa
nested = pa.array([
{"x": 1, "tags": ["a", "b"]},
{"x": 2, "tags": []},
])
print(nested.type)The inferred type is struct<x: int64, tags: list<item: string>>. A struct column is stored as one child array per field, plus a validity bitmap for the struct itself. A struct can be null as a whole, and a child can be null inside a struct that is not.
Common errors
- Inferred
nulltype. An all-Nonecolumn gets typenull. Declare the type. - Unit mismatch. Comparing or joining
timestamp[ms]andtimestamp[ns]columns needs an explicit cast. - Schema mismatch on write. Writing a batch to an existing stream or file with a different schema raises an error. Cast first.
- Overflow on cast.
ArrowInvalidfromcastmeans a value did not fit. Check the data, or widen the target type. - Assuming
nullable=Falseis enforced. Validate the data yourself if it matters.
Exercise
A column of IDs arrives as pa.array([1, 2, 3]). A downstream tool needs int32. You call arr.cast(pa.int32()). Is the result a view of the original memory? What happens if one ID is 5,000,000,000?
Show answer
No. The original array is int64, and int32 needs 4 bytes per value instead of 8, so the cast allocates a new buffer and copies every value. With the value 5,000,000,000, which does not fit in int32, a safe cast raises pa.ArrowInvalid. Passing safe=False would wrap the value silently, which is usually wrong.
Exercise
You build a table with pa.table({"flag": [None, None]}). What type does the flag column get, and how do you make it bool instead?
Show answer
The column gets the null type, because there are no values to infer from. Pass a schema, for example pa.table({"flag": [None, None]}, schema=pa.schema([("flag", pa.bool_())])), or build the array with pa.array([None, None], type=pa.bool_()).