Working with column metadata¶
Add column labels, definitions, units and code labels to parquet files to make reports easier to read. See the Column metadata convention for the recommended fields and how to use them with polars alone.
Create a documented parquet file¶
Use ps.Metadata() to build metadata for df.write_parquet().
import polars as pl
import polarstory as ps
# example data
df = pl.DataFrame({'age': [42, 53], 'diabetes': [0, 1]})
# document the columns
md = (
ps.Metadata()
.add('age', label='Age at cohort entry', unit='years', kind='continuous')
.add('diabetes', label='Diabetes diagnosis', value_labels={0: 'No', 1: 'Yes'})
)
# write data and metadata together
df.write_parquet('cohort.parquet', metadata=md.to_polars())
to_polars() produces the encoded metadata for polars. to_columns() returns
the nested column dictionary.
Read metadata and create a data dictionary¶
# read raw column metadata
columns = ps.read_column_metadata('cohort.parquet')
print(columns['age'])
# display the dictionary without scanning observations
print(ps.data_dictionary('cohort.parquet'))
# export to csv
ps.data_dictionary('cohort.parquet').write_csv('dictionary.csv')
The dictionary includes the column name, dtype and populated metadata fields. Columns without documentation are included as well.
For the example dataset, the dictionary looks like this:
| column | dtype | label | kind | value_labels | unit |
|---|---|---|---|---|---|
| age | Int64 | Age at cohort entry | continuous | years | |
| diabetes | Int64 | Diabetes diagnosis | 0 = No; 1 = Yes |
Select particular dataset columns or metadata fields:
# select dataset columns
ps.data_dictionary('cohort.parquet', columns=['age'])
# select and order dictionary fields
ps.data_dictionary('cohort.parquet', metadata=['label', 'unit'])
# use metadata with an in-memory dataframe
ps.data_dictionary(df, metadata=md.to_columns())
Profiles and reports¶
Profiles include a Data Dictionary section above Variable Inventory when column metadata is available. This also works with right-click reports.
# generate an automatic report
p = ps.profile('cohort.parquet')
p.write_html('cohort.html')
# access the dictionary from a profile
print(p.data_dictionary)
Add a dictionary to a custom report from a file or an existing profile:
report = ps.Report('Cohort documentation')
report.add_data_dictionary('cohort.parquet')
report.add(p.summary('age'))
report.add(p.frequency('diabetes'))
report.write_html('documentation.html')
# reuse the profile's column selection and settings
report = ps.Report('Selected variables')
report.add_data_dictionary(p)
report.write_html('selected.html')
Select or disable metadata¶
metadata |
Behavior |
|---|---|
| omitted | Read columns and display all populated fields |
['label', 'unit'] |
Display selected metadata fields, in order |
'my_columns' |
Read a different parquet metadata key |
None |
Ignore embedded metadata |
| nested dictionary | Use supplied column metadata |
# limit the dictionary fields
ps.profile('cohort.parquet', metadata=['label', 'kind', 'unit'])
# use a custom key
ps.profile('cohort.parquet', metadata='my_columns')
# ignore embedded metadata
ps.profile('cohort.parquet', metadata=None)
Field selection only changes the dictionary display. Use Variables to change
profiling settings or override a stored label.
variables = ps.Variables().set(
'diabetes', label='Baseline diabetes', kind='categorical',
)
p = ps.profile('cohort.parquet', variables=variables)
kindin parquet metadata is descriptive; it does not set the analytical type.- Sensitive value labels are hidden by default. Use
include_sensitive=Trueindata_dictionary()orProfileOptionsto include them. metadata=Nonealso ignores embedded sensitivity settings.
CLI and right-click reports¶
Use the metadata options with profile, inspect or diagnose:
polarstory profile cohort.parquet --metadata-fields label kind unit --open
polarstory inspect cohort.parquet --metadata-key my_columns
polarstory diagnose cohort.parquet --no-metadata
Set defaults for CLI and right-click reports in polarstory.toml, in the
working directory or next to the parquet file:
[profile]
metadata_key = "columns"
read_metadata = true
metadata_fields = ["label", "kind", "description", "unit"]
Omit metadata_fields to display all fields or to use a custom metadata_key.
Edit existing parquet files¶
Use ps.Metadata(path) to edit the metadata of an existing file. Changes are
saved only when you call write(); data pages are not decoded or recompressed.
# update the original file
(
ps.Metadata('cohort.parquet')
.add('age', description='Completed years of age on the index date')
.add('diabetes', kind='binary')
.write()
)
Adding an attribute replaces its previous value but leaves other attributes
unchanged. A new value_labels mapping replaces the entire previous mapping.
# add documentation to several columns
columns = {
'age': {'group': 'Demographics', 'source': 'Enrollment'},
'diabetes': {'group': 'Comorbidities'},
}
ps.Metadata('cohort.parquet').update(columns).write()
# remove one attribute
ps.Metadata('cohort.parquet').remove('age', 'source').write()
# remove all documentation for a column in a separate copy
ps.Metadata('cohort.parquet').remove('diabetes').write('documented.parquet')
remove() only removes metadata, not data columns. To replace an existing
output file, pass overwrite=True. For a custom metadata key, use
ps.Metadata(path, key='my_columns').
Large files and in-place updates¶
By default, write() copies the data in 8 MiB chunks and atomically replaces
the original file.
Use inplace=True to rewrite only the footer of the original file:
ps.Metadata('cohort.parquet').add('age', label='Age').write(inplace=True)
In-place updates are not atomic
An interrupted write or system failure can corrupt the parquet file.
- Keep a backup before using
inplace=True. - Ensure exclusive access to the file while writing.
- Prefer
inplace=Falsewhen disk space permits.
The editor supports local, unencrypted parquet files. Atomic replacement may change filesystem attributes, such as ownership or access permissions.
Preserve metadata when rewriting data¶
Reading and rewriting a parquet file with polars does not automatically carry
forward its column documentation. Read it separately and pass it to
write_parquet().
# read the data and its documentation
md = ps.Metadata('cohort.parquet')
df = pl.read_parquet('cohort.parquet')
# filter observations and keep the same metadata
df = df.filter(pl.col('age') >= 50)
df.write_parquet('older_patients.parquet', metadata=md.to_polars())
If you rename or drop columns, update their metadata as well.
# rename a column and its metadata
md = ps.Metadata('cohort.parquet')
columns = md.to_columns()
df = pl.read_parquet('cohort.parquet').rename({'age': 'baseline_age'})
columns['baseline_age'] = columns.pop('age')
# write the renamed dataset
df.write_parquet(
'renamed.parquet',
metadata=ps.Metadata().update(columns).to_polars(),
)
To carry forward other file-level metadata, read it separately with
pl.read_parquet_metadata(). Do not reuse the original ARROW:schema key
when writing a changed schema.