Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

PyBIDS

Run this notebook

A Python API for working with BIDS datasets

Author: Monika Doerig

Date: 4 June 2025

License:

MIT License

Note: If this notebook uses neuroimaging tools from Neurocontainers, those tools retain their original licenses. Please see Neurodesk citation guidelines for details.

Citation and Resources:

Data from OpenNeuro

  • Gorgolewski KJ and Storkey A and Bastin ME and Whittle IR and Wardlaw JM and Pernet CR (2022). A test-retest fMRI dataset for motor, language and spatial attention functions. OpenNeuro. [Dataset] doi: doiGorgolewski KJ et al. (2022)

Tools included in this workflow

pyBIDS:

  • Yarkoni et al., (2019). PyBIDS: Python tools for BIDS datasets. Journal of Open Source Software, 4(40), 1294, https://doi.org/10.21105/joss.01294

  • Yarkoni, T., Markiewicz, C. J., de la Vega, A., Gorgolewski, K. J., Salo, T., Gau, R., Halchenko, Y. O., Papadopoulos Orfanos, D., Esteban, O., McNamara, Q., DeStasio, K., Poline, J.-B., Johnson, H., Kalenkovich, E., Petrov, D., Nielson, D. M., James Kent, Kent, J. D., Appelhoff, S., … pierre-nedelec. (2024). PyBIDS: Python tools for BIDS datasets (0.18.1). Zenodo. Yarkoni et al. (2024)

Educational resources

Installation

PyBIDS simplifies the process of querying, summarizing, and managing data for neuroimaging researchers using the BIDS standard. Several Python packages for neuroimaging analysis—such as Nipype and Nilearn—are designed to integrate seamlessly with BIDS-formatted datasets

Data download

Fetching long content....
Fetching long content....

Querying BIDS datasets

Loading BIDS datasets

The BIDSLayout instance is a lightweight container for all of the files in the BIDS project directory. It automatically detects any BIDS entities found in the file paths, and allows us to perform simple but relatively powerful queries over the file tree. By default, defined BIDS entities include things like “subject”, “session”, “run”, and “type”.

Querying the BIDSLayout using get

When a BIDSLayout is initialized, it scans and indexes all files and metadata within the specified root directory. Once the indexing is complete, you can start exploring the dataset through different types of queries. The main method for this is .get(). If you call .get() without any arguments, it simply returns a list of all BIDS files in the dataset:

There are 174 files in the layout.

The first 3 files are:
[<BIDSFile filename='/home/jovyan/workspace/books/examples/workflows/ds000114/CHANGES'>, <BIDSJSONFile filename='/home/jovyan/workspace/books/examples/workflows/ds000114/dataset_description.json'>, <BIDSFile filename='/home/jovyan/workspace/books/examples/workflows/ds000114/dwi.bval'>]

In this Python list, each element is a BIDSFile object. If you want to work with just file names, you can simpliy it with:

['/home/jovyan/workspace/books/examples/workflows/ds000114/CHANGES', '/home/jovyan/workspace/books/examples/workflows/ds000114/dataset_description.json', '/home/jovyan/workspace/books/examples/workflows/ds000114/dwi.bval']

Common BIDS Entities:

The .get()method supports various arguments that let us narrow down the results based on specific criteria. Any BIDS-defined keywords - referred to as entities in PyBIDS - can be used as filters. Here are the most common ones:

suffix: The part of a BIDS filename just before the extension (e.g., ‘bold’, ‘events’, ‘physio’, etc.).

subject: The subject label

session: The session label

run: The run index

task: The task name

{'subject': <Entity subject (pattern=[/\\]+sub-([a-zA-Z0-9+]+), dtype=<class 'str'>)>, 'session': <Entity session (pattern=[_/\\]+ses-([a-zA-Z0-9+]+), dtype=<class 'str'>)>, 'sample': <Entity sample (pattern=[_/\\]+sample-([a-zA-Z0-9+]+), dtype=<class 'str'>)>, 'task': <Entity task (pattern=[_/\\]+task-([a-zA-Z0-9+]+), dtype=<class 'str'>)>, 'tracksys': <Entity tracksys (pattern=[_/\\]+tracksys-([a-zA-Z0-9+]+), dtype=<class 'str'>)>, 'acquisition': <Entity acquisition (pattern=[_/\\]+acq-([a-zA-Z0-9+]+), dtype=<class 'str'>)>, 'nucleus': <Entity nucleus (pattern=[_/\\]+nuc-([a-zA-Z0-9+]+), dtype=<class 'str'>)>, 'volume': <Entity volume (pattern=[_/\\]+voi-([a-zA-Z0-9+]+), dtype=<class 'str'>)>, 'ceagent': <Entity ceagent (pattern=[_/\\]+ce-([a-zA-Z0-9+]+), dtype=<class 'str'>)>, 'staining': <Entity staining (pattern=[_/\\]+stain-([a-zA-Z0-9+]+), dtype=<class 'str'>)>, 'tracer': <Entity tracer (pattern=[_/\\]+trc-([a-zA-Z0-9+]+), dtype=<class 'str'>)>, 'reconstruction': <Entity reconstruction (pattern=[_/\\]+rec-([a-zA-Z0-9+]+), dtype=<class 'str'>)>, 'direction': <Entity direction (pattern=[_/\\]+dir-([a-zA-Z0-9+]+), dtype=<class 'str'>)>, 'run': <Entity run (pattern=[_/\\]+run-(\d+), dtype=<class 'bids.layout.utils.PaddedInt'>)>, 'proc': <Entity proc (pattern=[_/\\]+proc-([a-zA-Z0-9+]+), dtype=<class 'str'>)>, 'modality': <Entity modality (pattern=[_/\\]+mod-([a-zA-Z0-9+]+), dtype=<class 'str'>)>, 'echo': <Entity echo (pattern=[_/\\]+echo-([0-9]+), dtype=<class 'str'>)>, 'flip': <Entity flip (pattern=[_/\\]+flip-([0-9]+), dtype=<class 'str'>)>, 'inv': <Entity inv (pattern=[_/\\]+inv-([0-9]+), dtype=<class 'str'>)>, 'mt': <Entity mt (pattern=[_/\\]+mt-(on|off), dtype=<class 'str'>)>, 'part': <Entity part (pattern=[_/\\]+part-(imag|mag|phase|real), dtype=<class 'str'>)>, 'recording': <Entity recording (pattern=[_/\\]+recording-([a-zA-Z0-9+]+), dtype=<class 'str'>)>, 'space': <Entity space (pattern=[_/\\]+space-([a-zA-Z0-9+]+), dtype=<class 'str'>)>, 'chunk': <Entity chunk (pattern=[_/\\]+chunk-([0-9]+), dtype=<class 'str'>)>, 'suffix': <Entity suffix (pattern=(?:^|[_/\\])([a-zA-Z0-9+]+)\.[^/\\]+$, dtype=<class 'str'>)>, 'scans': <Entity scans (pattern=(.*\_scans.tsv)$, dtype=<class 'str'>)>, 'fmap': <Entity fmap (pattern=(phasediff|magnitude[1-2]|phase[1-2]|fieldmap|epi)\.nii, dtype=<class 'str'>)>, 'datatype': <Entity datatype (pattern=[/\\]+(anat|beh|dwi|eeg|fmap|func|ieeg|meg|micr|motion|mrs|nirs|perf|pet)[/\\]+, dtype=<class 'str'>)>, 'extension': <Entity extension (pattern=[^./\\](\.[^/\\]+)$, dtype=<class 'str'>)>, 'EchoTime': <Entity EchoTime (pattern=None, dtype=<class 'str'>)>, 'FlipAngle': <Entity FlipAngle (pattern=None, dtype=<class 'str'>)>, 'RepetitionTime': <Entity RepetitionTime (pattern=None, dtype=<class 'str'>)>, 'SliceTiming': <Entity SliceTiming (pattern=None, dtype=<class 'str'>)>, 'TaskName': <Entity TaskName (pattern=None, dtype=<class 'str'>)>}

Query by subjects:

['01', '02', '03', '04', '05', '06', '07', '08', '09', '10']

Query by sessions:

['retest', 'test']

Query by tasks:

['covertverbgeneration', 'fingerfootlips', 'linebisection', 'overtverbgeneration', 'overtwordrepetition']

Here’s how we would retrieve all BOLD runs with .nii.gz extensions for subject ‘02’:

['/home/jovyan/workspace/books/examples/workflows/ds000114/sub-02/ses-retest/func/sub-02_ses-retest_task-covertverbgeneration_bold.nii.gz', '/home/jovyan/workspace/books/examples/workflows/ds000114/sub-02/ses-retest/func/sub-02_ses-retest_task-fingerfootlips_bold.nii.gz', '/home/jovyan/workspace/books/examples/workflows/ds000114/sub-02/ses-retest/func/sub-02_ses-retest_task-linebisection_bold.nii.gz', '/home/jovyan/workspace/books/examples/workflows/ds000114/sub-02/ses-retest/func/sub-02_ses-retest_task-overtverbgeneration_bold.nii.gz', '/home/jovyan/workspace/books/examples/workflows/ds000114/sub-02/ses-retest/func/sub-02_ses-retest_task-overtwordrepetition_bold.nii.gz', '/home/jovyan/workspace/books/examples/workflows/ds000114/sub-02/ses-test/func/sub-02_ses-test_task-covertverbgeneration_bold.nii.gz', '/home/jovyan/workspace/books/examples/workflows/ds000114/sub-02/ses-test/func/sub-02_ses-test_task-fingerfootlips_bold.nii.gz', '/home/jovyan/workspace/books/examples/workflows/ds000114/sub-02/ses-test/func/sub-02_ses-test_task-linebisection_bold.nii.gz', '/home/jovyan/workspace/books/examples/workflows/ds000114/sub-02/ses-test/func/sub-02_ses-test_task-overtverbgeneration_bold.nii.gz', '/home/jovyan/workspace/books/examples/workflows/ds000114/sub-02/ses-test/func/sub-02_ses-test_task-overtwordrepetition_bold.nii.gz']

Extracting metadata

All the entities mentioned above are derived from the filenames in a BIDS dataset. However, sometimes we want to filter files not just by their names, but also using metadata defined in sidecar JSON files, as specified by the BIDS standard. When a BIDSLayout is initialized, it automatically indexes all associated metadata files. This means we can use any key found in a JSON file as a filter in .get(), and we can even combine these with core BIDS entities like subject, run, and task.

For example, suppose we want to retrieve all files that meet the following criteria: (a) the RepetitionTime metadata value is 2.5, (b) the task is either ‘covert_verb_generation’ or ‘finger_foot_lips’, and (c) the subject is ‘01’ or ‘02’.

Here’s how we can do that:

[<BIDSImageFile filename='/home/jovyan/workspace/books/examples/workflows/ds000114/sub-01/ses-retest/func/sub-01_ses-retest_task-covertverbgeneration_bold.nii.gz'>, <BIDSImageFile filename='/home/jovyan/workspace/books/examples/workflows/ds000114/sub-01/ses-retest/func/sub-01_ses-retest_task-fingerfootlips_bold.nii.gz'>, <BIDSImageFile filename='/home/jovyan/workspace/books/examples/workflows/ds000114/sub-01/ses-test/func/sub-01_ses-test_task-covertverbgeneration_bold.nii.gz'>, <BIDSImageFile filename='/home/jovyan/workspace/books/examples/workflows/ds000114/sub-01/ses-test/func/sub-01_ses-test_task-fingerfootlips_bold.nii.gz'>, <BIDSImageFile filename='/home/jovyan/workspace/books/examples/workflows/ds000114/sub-02/ses-retest/func/sub-02_ses-retest_task-covertverbgeneration_bold.nii.gz'>, <BIDSImageFile filename='/home/jovyan/workspace/books/examples/workflows/ds000114/sub-02/ses-retest/func/sub-02_ses-retest_task-fingerfootlips_bold.nii.gz'>, <BIDSImageFile filename='/home/jovyan/workspace/books/examples/workflows/ds000114/sub-02/ses-test/func/sub-02_ses-test_task-covertverbgeneration_bold.nii.gz'>, <BIDSImageFile filename='/home/jovyan/workspace/books/examples/workflows/ds000114/sub-02/ses-test/func/sub-02_ses-test_task-fingerfootlips_bold.nii.gz'>]

The BIDSFile

Calling .get() on a BIDSLayout returns a list of BIDSFile objects by default. These are lightweight representations of individual files within a BIDS dataset and offer convenient access to various attributes and methods. Let’s explore what a BIDSFile can do. To start, we’ll select a random file from the layout.

<BIDSImageFile filename='/home/jovyan/workspace/books/examples/workflows/ds000114/sub-01/ses-retest/func/sub-01_ses-retest_task-overtverbgeneration_bold.nii.gz'>

A BIDSFile provides a convenient interface to interact with individual files in a BIDS dataset. Depending on the file type, different attributes and methods are available. Keep in mind that some methods are only applicable to specific types of files—for example, you can’t use .get_image() on a non-image file.

Here are some commonly used attributes and methods:

.path – Full path to the file

.filename – Name of the file (excluding the directory)

.dirname – Directory where the file is located

.get_entities() – Returns a dictionary of entities (e.g., subject, task) associated with the file; metadata can be optionally included

.get_image() – Loads the file as a nibabel image (only valid for image files)

.get_df() – Loads the file into a pandas DataFrame (works for .tsv files)

.get_metadata() – Retrieves a dictionary of metadata from the related JSON sidecar(s)

.get_associations() – Lists other files that are linked to this one (e.g., JSON, events, or anatomical associations)

{'datatype': 'func', 'extension': '.nii.gz', 'session': 'retest', 'subject': '01', 'suffix': 'bold', 'task': 'overtverbgeneration'}
{'EchoTime': 0.05, 'FlipAngle': 90, 'RepetitionTime': 5.0, 'SliceTiming': [0.0, 1.2499999999999998, 0.08333333333333333, 1.333333333333333, 0.16666666666666666, 1.4166666666666663, 0.25, 1.4999999999999996, 0.3333333333333333, 1.5833333333333328, 0.41666666666666663, 1.666666666666666, 0.5, 1.7499999999999993, 0.5833333333333333, 1.8333333333333326, 0.6666666666666666, 1.9166666666666659, 0.75, 1.9999999999999991, 0.8333333333333333, 2.083333333333332, 0.9166666666666666, 2.1666666666666656, 1.0, 2.249999999999999, 1.0833333333333333, 2.333333333333332, 1.1666666666666665, 2.416666666666665], 'TaskName': 'overt_verb_generation'}
{'EchoTime': 0.05, 'FlipAngle': 90, 'RepetitionTime': 5.0, 'SliceTiming': [0.0, 1.2499999999999998, 0.08333333333333333, 1.333333333333333, 0.16666666666666666, 1.4166666666666663, 0.25, 1.4999999999999996, 0.3333333333333333, 1.5833333333333328, 0.41666666666666663, 1.666666666666666, 0.5, 1.7499999999999993, 0.5833333333333333, 1.8333333333333326, 0.6666666666666666, 1.9166666666666659, 0.75, 1.9999999999999991, 0.8333333333333333, 2.083333333333332, 0.9166666666666666, 2.1666666666666656, 1.0, 2.249999999999999, 1.0833333333333333, 2.333333333333332, 1.1666666666666665, 2.416666666666665], 'TaskName': 'overt_verb_generation', 'datatype': 'func', 'extension': '.nii.gz', 'session': 'retest', 'subject': '01', 'suffix': 'bold', 'task': 'overtverbgeneration'}
[<BIDSJSONFile filename='/home/jovyan/workspace/books/examples/workflows/ds000114/task-overtverbgeneration_bold.json'>]

Exporting a BIDSLayout to a pandas Dataframe

If you’re looking for a high-level overview of all the files in your BIDSLayout without manually iterating through each BIDSFile and extracting their entities, the .to_df() method offers a convenient solution. It provides a structured summary of the dataset in the form of a pandas DataFrame.

Loading...
Loading...

BIDS Validator

PyBIDS includes an implicit import of the BIDSValidator class from the separate bids-validator package. This class can be used to check whether a given file path conforms to BIDS naming conventions and to infer what type of data the file represents.

However, it’s important to note that the Python-based validator may lag behind the official JavaScript implementation available online. Additionally, the Python version only validates individual file paths - it doesn’t support validation of an entire BIDS dataset. For full dataset validation, it’s recommended to use the online BIDS Validator.

True
True
True
False
False

Dependencies in Jupyter/Python

  • Using the package watermark to document system environment and software versions used in this notebook, alongside the Neurodesktop version extracted from the JUPYTER_IMAGE or NEURODESKTOP_VERSION environment variables.

Last updated: 2026-04-09T04:09:44.540175+00:00

Python implementation: CPython
Python version       : 3.13.9
IPython version      : 9.7.0

Compiler    : GCC 14.3.0
OS          : Linux
Release     : 5.15.0-171-generic
Machine     : x86_64
Processor   : x86_64
CPU cores   : 32
Architecture: 64bit

bids          : 0.21.0
bids_validator: 1.14.7.post0

Neurodesktop version: 2025-12-20
References
  1. Gorgolewski KJ, Storkey A, Bastin ME, Whittle IR, Wardlaw JM, & Pernet CR. (2022). A test-retest fMRI dataset for motor, language and spatial attention functions. OpenNeuro. 10.18112/OPENNEURO.DS000114.V1.0.2
  2. Yarkoni, T., Markiewicz, C. J., de la Vega, A., Gorgolewski, K. J., Salo, T., Gau, R., Halchenko, Y. O., Papadopoulos Orfanos, D., Esteban, O., McNamara, Q., DeStasio, K., Poline, J.-B., Johnson, H., Kalenkovich, E., Petrov, D., Nielson, D. M., James Kent, Kent, J. D., Appelhoff, S., … pierre nedelec. (2024). PyBIDS: Python tools for BIDS datasets. Zenodo. 10.5281/ZENODO.14285569