Sub topic 1
Refresher: Arrow tables and schemas
This chapter reviews the Arrow objects that every later chapter relies on: arrays, schemas, tables and record batches. Partitioned datasets are built on these types. When a dataset reports a schema, hands you a batch, or asks for a partition field type, it is using the objects described here.
Prerequisites
This chapter assumes you have the following:
- Basic Python, including functions, dictionaries and lists.
- Familiarity with tables and columns, for example from pandas or SQL.
- A rough idea of what a Parquet file is. The next chapter covers the details.
- Awareness of local file systems and paths.
- PyArrow installed (
pip install pyarrow). The examples work with any recent release.
Why start with tables and schemas
A dataset is a lazy view over many files. When you read from it, you get Arrow data back, and when you write to it, you pass Arrow data in. Three things from this chapter come up repeatedly:
- The schema of a dataset describes both the columns stored in the files and the columns encoded in directory names.
- A table is what
dataset.to_table()returns. - A record batch is the unit you receive when you stream data from a scanner.
Arrays and types
Arrow stores data by column. A column of values with one type is an array. Each array has a fixed type, such as int64, float64, string or timestamp, and it can contain nulls.
import pyarrow as pa
years = pa.array([2023, 2023, 2024, None])
countries = pa.array(["DE", "FR", "DE", "FR"])
print(years.type) # int64
print(countries.type) # string
print(years.null_count) # 1Python integers become int64 and Python floats become double (the same as float64) unless you ask for something else. Pass type= to choose a narrower type:
import pyarrow as pa
small_years = pa.array([2023, 2024], type=pa.int16())
print(small_years.type) # int16Type choice matters for partitioning. A partition value read from a directory name is converted to the type you declare, so year=2023 can become an int16 or an int64. Later chapters return to this.
Fields and schemas
A field is a column name plus a type, with an optional nullable flag. A schema is an ordered list of fields.
import pyarrow as pa
schema = pa.schema([
pa.field("year", pa.int64()),
pa.field("country", pa.string()),
pa.field("amount", pa.float64()),
])
print(schema)
print(schema.names)
print(schema.field("amount").type)A shorthand form accepts (name, type) tuples, which is what the partitioning examples in later chapters use:
import pyarrow as pa
schema = pa.schema([("year", pa.int64()), ("country", pa.string())])
print(schema)Schemas can also carry key-value metadata. Parquet writers use this to store information such as the original pandas index. You rarely need to touch it, but it is a reason two schemas that look alike can compare unequal. Use schema.equals(other, check_metadata=True) when you need to compare metadata too.
Tables
A table is a schema plus a set of equal-length columns. You can build one from a dictionary, as the dataset examples in this tutorial do:
import pyarrow as pa
table = pa.table({
"year": [2023, 2023, 2024, 2024],
"country": ["DE", "FR", "DE", "FR"],
"amount": [10.5, 20.0, 7.25, 3.0],
})
print(table.schema)
print(table.num_rows, table.num_columns)
print(table.column("amount"))
print(table.to_pydict())You can also pass an explicit schema, which gives you control over types and prevents inference surprises:
import pyarrow as pa
schema = pa.schema([("year", pa.int16()), ("amount", pa.float32())])
table = pa.table({"year": [2023, 2024], "amount": [1.5, 2.5]}, schema=schema)
print(table.schema)Table columns are chunked arrays. A chunked array is a column stored as one or more separate arrays that behave as one. A table read from many files is usually chunked, because each file or batch contributes its own chunk. table.column("amount").num_chunks shows how many chunks a column has. Most operations work the same regardless of chunking. If you need a single contiguous array, call table.combine_chunks() first.
Record batches
A record batch is like a table whose columns are plain arrays, not chunked arrays. It is a single block of rows with a schema. Batches are the natural unit for streaming, because each one is small and has a known size.
import pyarrow as pa
batch = pa.record_batch({
"country": ["DE", "FR"],
"amount": [10.5, 20.0],
})
print(batch.num_rows)
print(batch.schema)
table = pa.Table.from_batches([batch, batch])
print(table.num_rows) # 4
print(table.column("amount").num_chunks) # 2A table can be split into batches with table.to_batches(). The scanner chapters show how to receive batches from a dataset one at a time, so memory use stays bounded.
How the pieces relate
The following diagram shows how the objects nest inside each other.
Inspecting and changing schemas
Four schema operations come up often with datasets.
- Selecting columns.
table.select(["country", "amount"])returns a new table with only those columns, in that order. Datasets do the same thing through thecolumns=argument. - Casting.
table.cast(new_schema)converts each column to the new type. It fails by default if a value does not fit, for example a large integer cast toint8. - Adding a column.
table.append_column("flag", pa.array([...]))returns a new table. Tables are immutable, so every change returns a new object. - Unifying schemas.
pa.unify_schemas([a, b])merges schemas and fails if the same name has conflicting types. Dataset discovery faces the same question when files disagree.
import pyarrow as pa
a = pa.schema([("year", pa.int64()), ("amount", pa.float64())])
b = pa.schema([("year", pa.int64()), ("country", pa.string())])
print(pa.unify_schemas([a, b]).names) # ['year', 'amount', 'country']Nullability and missing values
Fields are nullable by default. A null is stored in a separate validity bitmap, not as a special value, so an integer column can hold nulls without becoming a float. This differs from pandas, where an integer column with missing values is converted to floating point unless you use a nullable dtype.
Nulls matter for partitioning. A row whose partition value is null has no sensible directory name. Writers handle this in a specific way, which the pitfalls chapter covers. Cleaning or filling the partition columns before writing is the safest approach.
Moving between pandas and Arrow
pa.Table.from_pandas(df) converts a DataFrame, and table.to_pandas() converts back. Two details matter:
- By default,
from_pandasmay store the pandas index as an extra column named__index_level_0__. Passpreserve_index=Falseto drop a plain default index. - String columns in pandas use the
objectdtype, and Arrow infersstring. Mixed-type object columns raise an error, so check them before converting.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `ArrowInvalid: Could not convert ... with type str: tried to convert to int64` | A list mixes types, or the schema disagrees with the data | Pass an explicit schema or clean the values |
| `ArrowInvalid: Integer value ... not in range` on `cast` | The target type is too narrow | Use a wider type, or check the value range first |
| `ArrowInvalid: Schema at index 1 was different` from `Table.from_batches` or `concat_tables` | Batches or tables have different schemas | Cast to a common schema first |
| Extra `__index_level_0__` column | pandas index preserved | Use `preserve_index=False` |
What comes next
The next chapter looks at Parquet files, which store Arrow tables on disk as row groups and column chunks. After that, the tutorial builds the dataset abstraction on top of these files and schemas.
Exercise
You build a table with pa.table({"year": [2023, 2024], "amount": [1.5, 2.5]}). What types does Arrow infer, and how would you get year as int16 and amount as float32?
Show answer
Arrow infers int64 for year and double (float64) for amount. Pass an explicit schema, for example pa.table({...}, schema=pa.schema([("year", pa.int16()), ("amount", pa.float32())])), or call table.cast(schema) on the inferred table.
Exercise
A table was built from three record batches with pa.Table.from_batches. What does table.column("amount").num_chunks return, and why does a table read from many files often have several chunks?
Show answer
It returns 3, because each batch becomes one chunk of the column. A table read from many files has several chunks because each file or batch contributes its own arrays, and Arrow keeps them as a chunked array instead of copying them into one buffer. Call table.combine_chunks() if you need a single contiguous array.