| 1 |
""" |
| 2 |
|
| 3 |
.. _dynamictable-howtoguide: |
| 4 |
|
| 5 |
DynamicTable How-To Guide |
| 6 |
========================= |
| 7 |
|
| 8 |
This is a user guide to interacting with ``DynamicTable`` objects. |
| 9 |
|
| 10 |
""" |
| 11 |
|
| 12 |
############################################################################### |
| 13 |
# Introduction |
| 14 |
# ------------ |
| 15 |
# The :py:class:`~hdmf.common.table.DynamicTable` class represents a column-based table |
| 16 |
# to which you can add custom columns. It consists of a name, a description, a list of |
| 17 |
# row IDs, and a list of columns. Columns are represented by objects of the class |
| 18 |
# :py:class:`~hdmf.common.table.VectorData`, including subclasses of |
| 19 |
# :py:class:`~hdmf.common.table.VectorData`, such as :py:class:`~hdmf.common.table.VectorIndex`, |
| 20 |
# and :py:class:`~hdmf.common.table.DynamicTableRegion`. |
| 21 |
|
| 22 |
############################################################################### |
| 23 |
# Constructing a table |
| 24 |
# -------------------- |
| 25 |
# To create a :py:class:`~hdmf.common.table.DynamicTable`, call the constructor for |
| 26 |
# :py:class:`~hdmf.common.table.DynamicTable` with a string ``name`` and string |
| 27 |
# ``description``. Specifying the arguments with keywords is recommended. |
| 28 |
|
| 29 |
# sphinx_gallery_thumbnail_path = 'figures/gallery_thumbnail_dynamictable.png' |
| 30 |
from hdmf.common import DynamicTable |
| 31 |
|
| 32 |
table = DynamicTable( |
| 33 |
name='my_table', |
| 34 |
description='an example table', |
| 35 |
) |
| 36 |
|
| 37 |
############################################################################### |
| 38 |
# Initializing columns |
| 39 |
# -------------------- |
| 40 |
# You can create a :py:class:`~hdmf.common.table.DynamicTable` with particular |
| 41 |
# columns by passing a list or tuple of |
| 42 |
# :py:class:`~hdmf.common.table.VectorData` objects for the ``columns`` argument |
| 43 |
# in the constructor. |
| 44 |
# |
| 45 |
# If the :py:class:`~hdmf.common.table.VectorData` objects contain data values, |
| 46 |
# then each :py:class:`~hdmf.common.table.VectorData` object must contain the |
| 47 |
# same number of rows as each other. A list of row IDs may be passed into the |
| 48 |
# :py:class:`~hdmf.common.table.DynamicTable` constructor using the ``id`` |
| 49 |
# argument. If IDs are passed in, there should be the same number of rows as |
| 50 |
# the column data. If IDs are not passed in, then the IDs will be set to |
| 51 |
# ``range(len(column_data))`` by default. |
| 52 |
|
| 53 |
from hdmf.common import VectorData, VectorIndex |
| 54 |
|
| 55 |
col1 = VectorData( |
| 56 |
name='col1', |
| 57 |
description='column #1', |
| 58 |
data=[1, 2], |
| 59 |
) |
| 60 |
col2 = VectorData( |
| 61 |
name='col2', |
| 62 |
description='column #2', |
| 63 |
data=['a', 'b'], |
| 64 |
) |
| 65 |
|
| 66 |
# this table will have two rows with ids 0 and 1 |
| 67 |
table = DynamicTable( |
| 68 |
name='my table', |
| 69 |
description='an example table', |
| 70 |
columns=[col1, col2], |
| 71 |
) |
| 72 |
|
| 73 |
# this table will have two rows with ids 0 and 1 |
| 74 |
table_set_ids = DynamicTable( |
| 75 |
name='my table', |
| 76 |
description='an example table', |
| 77 |
columns=[col1, col2], |
| 78 |
id=[0, 1], |
| 79 |
) |
| 80 |
|
| 81 |
############################################################################### |
| 82 |
# If a list of integers in passed to ``id``, |
| 83 |
# :py:class:`~hdmf.common.table.DynamicTable` automatically creates |
| 84 |
# an :py:class:`~hdmf.common.table.ElementIdentifiers` object, which is the data type |
| 85 |
# that stores row IDs. The above command is equivalent to: |
| 86 |
|
| 87 |
from hdmf.common.table import ElementIdentifiers |
| 88 |
|
| 89 |
table_set_ids = DynamicTable( |
| 90 |
name='my table', |
| 91 |
description='an example table', |
| 92 |
columns=[col1, col2], |
| 93 |
id=ElementIdentifiers(name='id', data=[0, 1]), |
| 94 |
) |
| 95 |
|
| 96 |
############################################################################### |
| 97 |
# Adding rows |
| 98 |
# ----------- |
| 99 |
# You can also add rows to a :py:class:`~hdmf.common.table.DynamicTable` using |
| 100 |
# :py:meth:`DynamicTable.add_row <hdmf.common.table.DynamicTable.add_row>`. |
| 101 |
# A keyword argument for every column in the table must be supplied. |
| 102 |
# You may also supply an optional row ID. |
| 103 |
|
| 104 |
table.add_row( |
| 105 |
col1=3, |
| 106 |
col2='c', |
| 107 |
id=2, |
| 108 |
) |
| 109 |
|
| 110 |
############################################################################### |
| 111 |
# .. note:: |
| 112 |
# If no ID is supplied, the row ID is automatically set to the number of rows of the table prior to adding the new |
| 113 |
# row. This can result in duplicate IDs. In general, IDs should be unique, but this is not enforced by default. |
| 114 |
# Pass `enforce_unique_id=True` to :py:meth:`DynamicTable.add_row <hdmf.common.table.DynamicTable.add_row>` |
| 115 |
# to raise an error if the ID is set to an existing ID value. |
| 116 |
|
| 117 |
# this row will have ID 3 by default |
| 118 |
table.add_row( |
| 119 |
col1=4, |
| 120 |
col2='d', |
| 121 |
) |
| 122 |
|
| 123 |
############################################################################### |
| 124 |
# Adding columns |
| 125 |
# -------------- |
| 126 |
# You can add columns to a :py:class:`~hdmf.common.table.DynamicTable` using |
| 127 |
# :py:meth:`DynamicTable.add_column <hdmf.common.table.DynamicTable.add_column>`. |
| 128 |
# If the table already has rows, then the ``data`` argument must be supplied |
| 129 |
# as a list of values, one for each row already in the table. |
| 130 |
|
| 131 |
table.add_column( |
| 132 |
name='col3', |
| 133 |
description='column #3', |
| 134 |
data=[True, True, False, True], # specify data for the 4 rows in the table |
| 135 |
) |
| 136 |
|
| 137 |
############################################################################### |
| 138 |
# Enumerated (categorical) data |
| 139 |
# ----------------------------- |
| 140 |
# :py:class:`~hdmf.common.table.EnumData` is a special type of column for storing |
| 141 |
# an enumerated data type. This way each unique value is stored once, and the data |
| 142 |
# references those values by index. Using this method is more efficient than storing |
| 143 |
# a single value many times, and has the advantage of communicating to downstream |
| 144 |
# tools that the data is categorical in nature. |
| 145 |
# |
| 146 |
# .. warning:: |
| 147 |
# |
| 148 |
# :py:class:`~hdmf.common.table.EnumData` is currently an experimental |
| 149 |
# feature and as such should not be used for production use. |
| 150 |
# |
| 151 |
|
| 152 |
from hdmf.common.table import EnumData |
| 153 |
import warnings |
| 154 |
warnings.filterwarnings(action="ignore", message="EnumData is experimental") |
| 155 |
|
| 156 |
# this column has a length of 5, not 3. the first row has value "aa" |
| 157 |
enum_col = EnumData( |
| 158 |
name='cell_type', |
| 159 |
description='this column holds categorical variables', |
| 160 |
data=[0, 1, 2, 1, 0], |
| 161 |
elements=['aa', 'bb', 'cc'] |
| 162 |
) |
| 163 |
|
| 164 |
my_table = DynamicTable( |
| 165 |
name='my_table', |
| 166 |
description='an example table', |
| 167 |
columns=[enum_col], |
| 168 |
) |
| 169 |
|
| 170 |
############################################################################### |
| 171 |
# Ragged array columns |
| 172 |
# -------------------- |
| 173 |
# A table column with a different number of elements for each row is called a |
| 174 |
# "ragged array column". To initialize a :py:class:`~hdmf.common.table.DynamicTable` |
| 175 |
# with a ragged array column, pass both |
| 176 |
# the :py:class:`~hdmf.common.table.VectorIndex` and its target |
| 177 |
# :py:class:`~hdmf.common.table.VectorData` in for the ``columns`` |
| 178 |
# argument in the constructor. For instance, the following code creates a column |
| 179 |
# called ``col1`` where the first cell is ['1a', '1b', '1c'] and the second cell |
| 180 |
# is ['2a']. |
| 181 |
|
| 182 |
col1 = VectorData( |
| 183 |
name='col1', |
| 184 |
description='column #1', |
| 185 |
data=['1a', '1b', '1c', '2a'], |
| 186 |
) |
| 187 |
# the 3 signifies that elements 0 to 3 (exclusive) of the target column belong to the first row |
| 188 |
# the 4 signifies that elements 3 to 4 (exclusive) of the target column belong to the second row |
| 189 |
col1_ind = VectorIndex( |
| 190 |
name='col1_index', |
| 191 |
target=col1, |
| 192 |
data=[3, 4], |
| 193 |
) |
| 194 |
|
| 195 |
table_ragged_col = DynamicTable( |
| 196 |
name='my table', |
| 197 |
description='an example table', |
| 198 |
columns=[col1, col1_ind], |
| 199 |
) |
| 200 |
|
| 201 |
#################################################################################### |
| 202 |
# .. note:: |
| 203 |
# By convention, the name of the :py:class:`~hdmf.common.table.VectorIndex` should be |
| 204 |
# the name of the target column with the added suffix "_index". |
| 205 |
|
| 206 |
#################################################################################### |
| 207 |
# VectorIndex.data provides the indices for how to break VectorData.data into cells |
| 208 |
# |
| 209 |
# You can add an empty ragged array column to an existing |
| 210 |
# :py:class:`~hdmf.common.table.DynamicTable` by specifying ``index=True`` |
| 211 |
# to :py:meth:`DynamicTable.add_column <hdmf.common.table.DynamicTable.add_column>`. |
| 212 |
# This method only works if run before any rows have been added to the table. |
| 213 |
|
| 214 |
new_table = DynamicTable( |
| 215 |
name='my_table', |
| 216 |
description='an example table', |
| 217 |
) |
| 218 |
|
| 219 |
new_table.add_column( |
| 220 |
name='col4', |
| 221 |
description='column #4', |
| 222 |
index=True, |
| 223 |
) |
| 224 |
|
| 225 |
############################################################################### |
| 226 |
# If the table already contains data, you must specify the new column values for |
| 227 |
# the existing rows using the ``data`` argument and you must specify the end indices of |
| 228 |
# the ``data`` argument that correspond to each row as a list/tuple/array of values for |
| 229 |
# the ``index`` argument. |
| 230 |
|
| 231 |
table.add_column( # <-- this table already has 4 rows |
| 232 |
name='col4', |
| 233 |
description='column #4', |
| 234 |
data=[1, 0, -1, 0, -1, 1, 1, -1], |
| 235 |
index=[3, 4, 6, 8], # specify the end indices (exclusive) of data for each row |
| 236 |
) |
| 237 |
|
| 238 |
############################################################################### |
| 239 |
# Alternatively we may also define the ragged array data as a nested list |
| 240 |
# and use the ``index`` argument to indicate the number of levels. In this case, |
| 241 |
# the :py:class:`~hdmf.common.table.DynamicTable.add_column` function will |
| 242 |
# automatically flatten the data array and compute the corresponding index vectors. |
| 243 |
|
| 244 |
table.add_column( # <-- this table already has 4 rows |
| 245 |
name='col5', |
| 246 |
description='column #5', |
| 247 |
data=[[[1, ], [2, 2]], # row 1 |
| 248 |
[[3, 3], ], # row 2 |
| 249 |
[[4, ], [5, 5]], # row 3 |
| 250 |
[[6, 6], [7, 7, 7]]], # row 4 |
| 251 |
index=2 # number of levels in the ragged array |
| 252 |
) |
| 253 |
# Show that the ragged array was converted to flat VectorData with a double VectorIndex |
| 254 |
print("Flattened data: %s" % str(table.col5.data)) |
| 255 |
print("Level 1 index: %s" % str(table.col5_index.data)) |
| 256 |
print("Level 2 index: %s" % str(table.col5_index_index.data)) |
| 257 |
|
| 258 |
|
| 259 |
############################################################################### |
| 260 |
# Referencing rows of other tables |
| 261 |
# -------------------------------- |
| 262 |
# You can create a column that references rows of another table by adding a |
| 263 |
# :py:class:`~hdmf.common.table.DynamicTableRegion` object as a column of your |
| 264 |
# :py:class:`~hdmf.common.table.DynamicTable`. This is analogous to |
| 265 |
# a foreign key in a relational database. |
| 266 |
|
| 267 |
from hdmf.common.table import DynamicTableRegion |
| 268 |
|
| 269 |
dtr_col = DynamicTableRegion( |
| 270 |
name='table1_ref', |
| 271 |
description='references rows of earlier table', |
| 272 |
data=[0, 1, 0, 0], # refers to row indices of the 'table' variable |
| 273 |
table=table |
| 274 |
) |
| 275 |
|
| 276 |
data_col = VectorData( |
| 277 |
name='col2', |
| 278 |
description='column #2', |
| 279 |
data=['a', 'a', 'a', 'b'], |
| 280 |
) |
| 281 |
|
| 282 |
table2 = DynamicTable( |
| 283 |
name='my_table', |
| 284 |
description='an example table', |
| 285 |
columns=[dtr_col, data_col], |
| 286 |
) |
| 287 |
|
| 288 |
############################################################################### |
| 289 |
# Here, the ``data`` of ``dtr_col`` maps to rows of ``table`` (0-indexed). |
| 290 |
# |
| 291 |
# .. note:: |
| 292 |
# The ``data`` values of :py:class:`~hdmf.common.table.DynamicTableRegion` map to the row |
| 293 |
# index, not the row ID, though if you are using default IDs, these values will be the |
| 294 |
# same. |
| 295 |
# |
| 296 |
# Reference more than one row of another table with a |
| 297 |
# :py:class:`~hdmf.common.table.DynamicTableRegion` indexed by a |
| 298 |
# :py:class:`~hdmf.common.table.VectorIndex`. |
| 299 |
|
| 300 |
indexed_dtr_col = DynamicTableRegion( |
| 301 |
name='table1_ref2', |
| 302 |
description='references multiple rows of earlier table', |
| 303 |
data=[0, 0, 1, 1, 0, 0, 1], |
| 304 |
table=table |
| 305 |
) |
| 306 |
|
| 307 |
# row 0 refers to rows [0, 0], row 1 refers to rows [1], row 2 refers to rows [1, 0], row 3 refers to rows [0, 1] of |
| 308 |
# the "table" variable |
| 309 |
dtr_idx = VectorIndex( |
| 310 |
name='table1_ref2_index', |
| 311 |
target=indexed_dtr_col, |
| 312 |
data=[2, 3, 5, 7], |
| 313 |
) |
| 314 |
|
| 315 |
table3 = DynamicTable( |
| 316 |
name='my_table', |
| 317 |
description='an example table', |
| 318 |
columns=[dtr_idx, indexed_dtr_col], |
| 319 |
) |
| 320 |
|
| 321 |
############################################################################### |
| 322 |
# Setting the target table of a DynamicTableRegion column of a DynamicTable |
| 323 |
# ------------------------------------------------------------------------- |
| 324 |
# A subclass of DynamicTable might have a pre-defined DynamicTableRegion column. |
| 325 |
# To write this column correctly, the "table" attribute of the column must be set so |
| 326 |
# that users know to what table the row index values reference. Because the target |
| 327 |
# table could be any table, the "table" attribute must be set explicitly. There are three |
| 328 |
# ways to do so. First, you can use the ``target_tables`` argument of the |
| 329 |
# DynamicTable constructor as shown below. This argument |
| 330 |
# is a dictionary mapping the name of the DynamicTableRegion column to |
| 331 |
# the target table. Secondly, the target table can be set after the DynamicTable |
| 332 |
# has been initialized using ``my_table.my_column.table = other_table``. Finally, |
| 333 |
# you can create the DynamicTableRegion column and pass the ``table`` |
| 334 |
# attribute to `DynamicTableRegion.__init__` and then pass the column to |
| 335 |
# `DynamicTable.__init__` using the `columns` argument. However, this approach |
| 336 |
# is not recommended for columns defined in the schema, because it is up to |
| 337 |
# the user to ensure that the column is created in accordance with the schema. |
| 338 |
|
| 339 |
class SubTable(DynamicTable): |
| 340 |
__columns__ = ( |
| 341 |
{'name': 'dtr', 'description': 'required region', 'required': True, 'table': True}, |
| 342 |
) |
| 343 |
|
| 344 |
referenced_table = DynamicTable( |
| 345 |
name='referenced_table', |
| 346 |
description='an example table', |
| 347 |
) |
| 348 |
|
| 349 |
sub_table = SubTable( |
| 350 |
name='sub_table', |
| 351 |
description='an example table', |
| 352 |
target_tables={'dtr': referenced_table}, |
| 353 |
) |
| 354 |
# now the target table of the DynamicTableRegion column 'dtr' is set to `referenced_table` |
| 355 |
|
| 356 |
############################################################################### |
| 357 |
# Creating an expandable table |
| 358 |
# ---------------------------- |
| 359 |
# When using the default HDF5 backend, each column of these tables is an HDF5 Dataset, |
| 360 |
# which by default are set in size. This means that once a file is written, it is not |
| 361 |
# possible to add a new row. If you want to be able to save this file, load it, and add |
| 362 |
# more rows to the table, you will need to set this up when you create the |
| 363 |
# :py:class:`~hdmf.common.table.DynamicTable`. You do this by wrapping the data with |
| 364 |
# :py:class:`~hdmf.backends.hdf5.h5_utils.H5DataIO` and the argument ``maxshape=(None, )``. |
| 365 |
|
| 366 |
from hdmf.backends.hdf5.h5_utils import H5DataIO |
| 367 |
|
| 368 |
col1 = VectorData( |
| 369 |
name='expandable_col1', |
| 370 |
description='column #1', |
| 371 |
data=H5DataIO(data=[1, 2], maxshape=(None,)), |
| 372 |
) |
| 373 |
col2 = VectorData( |
| 374 |
name='expandable_col2', |
| 375 |
description='column #2', |
| 376 |
data=H5DataIO(data=['a', 'b'], maxshape=(None,)), |
| 377 |
) |
| 378 |
|
| 379 |
# don't forget to wrap the row IDs too! |
| 380 |
ids = ElementIdentifiers( |
| 381 |
name='id', |
| 382 |
data=H5DataIO(data=[0, 1], maxshape=(None,)), |
| 383 |
) |
| 384 |
|
| 385 |
expandable_table = DynamicTable( |
| 386 |
name='expandable_table', |
| 387 |
description='an example table that can be expanded after being saved to a file', |
| 388 |
columns=[col1, col2], |
| 389 |
id=ids, |
| 390 |
) |
| 391 |
|
| 392 |
############################################################################### |
| 393 |
# Now you can write the file, read it back, and run ``expandable_table.add_row()``. |
| 394 |
# In this example, we are setting ``maxshape`` to ``(None,)``, which means this is a |
| 395 |
# 1-dimensional matrix that can expand indefinitely along its single dimension. You |
| 396 |
# could also use an integer in place of ``None``. For instance, ``maxshape=(8,)`` would |
| 397 |
# allow the column to grow up to a length of 8. Whichever ``maxshape`` you choose, |
| 398 |
# it should be the same for all :py:class:`~hdmf.common.table.VectorData` and |
| 399 |
# :py:class:`~hdmf.common.table.ElementIdentifiers` objects in the |
| 400 |
# :py:class:`~hdmf.common.table.DynamicTable`, since they must always be the same |
| 401 |
# length. The default :py:class:`~hdmf.common.table.ElementIdentifiers` automatically |
| 402 |
# generated when you pass a list of integers to the ``id`` argument of the |
| 403 |
# :py:class:`~hdmf.common.table.DynamicTable` constructor is not expandable, so do not |
| 404 |
# forget to create a :py:class:`~hdmf.common.table.ElementIdentifiers` object, and wrap |
| 405 |
# that data as well. If any of the columns are indexed, the ``data`` argument of |
| 406 |
# :py:class:`~hdmf.common.table.VectorIndex` will also need to be wrapped with |
| 407 |
# :py:class:`~hdmf.backends.hdf5.h5_utils.H5DataIO`. |
| 408 |
# |
| 409 |
# |
| 410 |
# Converting the table to a pandas ``DataFrame`` |
| 411 |
# ---------------------------------------------- |
| 412 |
# `pandas`_ is a popular data analysis tool, especially for working with tabular data. |
| 413 |
# You can convert your :py:class:`~hdmf.common.table.DynamicTable` to a |
| 414 |
# :py:class:`~pandas.DataFrame` using |
| 415 |
# :py:meth:`DynamicTable.to_dataframe <hdmf.common.table.DynamicTable.to_dataframe>`. |
| 416 |
# Accessing the table as a :py:class:`~pandas.DataFrame` provides you with powerful, |
| 417 |
# standard methods for indexing, selecting, and querying tabular data from `pandas`_. |
| 418 |
# This is the recommended method of reading data from your table. See also the `pandas indexing documentation`_. |
| 419 |
# Printing a :py:class:`~hdmf.common.table.DynamicTable` as a :py:class:`~pandas.DataFrame` |
| 420 |
# or displaying the :py:class:`~pandas.DataFrame` in Jupyter shows a more intuitive |
| 421 |
# tabular representation of the data than printing the |
| 422 |
# :py:class:`~hdmf.common.table.DynamicTable` object. |
| 423 |
# |
| 424 |
# .. _pandas: https://pandas.pydata.org/ |
| 425 |
# .. _`pandas indexing documentation`: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html |
| 426 |
|
| 427 |
df = table.to_dataframe() |
| 428 |
|
| 429 |
############################################################################### |
| 430 |
# .. note:: |
| 431 |
# |
| 432 |
# Changes to the ``DataFrame`` will not be saved in the ``DynamicTable``. |
| 433 |
|
| 434 |
############################################################################### |
| 435 |
# Converting the table from a pandas ``DataFrame`` |
| 436 |
# ------------------------------------------------ |
| 437 |
# If your data is already in a :py:class:`~pandas.DataFrame`, you can convert the |
| 438 |
# ``DataFrame`` to a :py:class:`~hdmf.common.table.DynamicTable` using the class method |
| 439 |
# :py:meth:`DynamicTable.from_dataframe <hdmf.common.table.DynamicTable.from_dataframe>`. |
| 440 |
|
| 441 |
table_from_df = DynamicTable.from_dataframe( |
| 442 |
name='my_table', |
| 443 |
df=df, |
| 444 |
) |
| 445 |
|
| 446 |
############################################################################### |
| 447 |
# Accessing elements |
| 448 |
# ------------------ |
| 449 |
# To access an element in the i-th row in the column with name "col_name" in a |
| 450 |
# :py:class:`~hdmf.common.table.DynamicTable`, use square brackets notation: |
| 451 |
# ``table[i, col_name]``. You can also use a tuple of row index and column |
| 452 |
# name within the square brackets. |
| 453 |
|
| 454 |
table[0, 'col1'] # returns 1 |
| 455 |
table[(0, 'col1')] # returns 1 |
| 456 |
|
| 457 |
############################################################################### |
| 458 |
# If the column is a ragged array, instead of a single value being returned, |
| 459 |
# a list of values for that element is returned. |
| 460 |
|
| 461 |
table[0, 'col4'] # returns [1, 0, -1] |
| 462 |
|
| 463 |
############################################################################### |
| 464 |
# Standard Python and numpy slicing can be used for the row index. |
| 465 |
|
| 466 |
import numpy as np |
| 467 |
|
| 468 |
table[:2, 'col1'] # get a list of elements from the first two rows at column 'col1' |
| 469 |
table[0:3:2, 'col1'] # get a list of elements from rows 0 to 3 (exclusive) in steps of 2 at column 'col1' |
| 470 |
table[3::-1, 'col1'] # get a list of elements from rows 3 to 0 in reverse order at column 'col1' |
| 471 |
|
| 472 |
# the following are equivalent to table[0:3:2, 'col1'] |
| 473 |
table[slice(0, 3, 2), 'col1'] |
| 474 |
table[np.s_[0:3:2], 'col1'] |
| 475 |
table[[0, 2], 'col1'] |
| 476 |
table[np.array([0, 2]), 'col1'] |
| 477 |
|
| 478 |
############################################################################### |
| 479 |
# If the column is a ragged array, instead of a list of row values being returned, |
| 480 |
# a list of list elements for the selected rows is returned. |
| 481 |
|
| 482 |
table[:2, 'col4'] # returns [[1, 0, -1], [0]] |
| 483 |
|
| 484 |
############################################################################### |
| 485 |
# .. note:: |
| 486 |
# |
| 487 |
# You cannot supply a list/tuple for the column name. For this |
| 488 |
# kind of access, first convert the :py:class:`~hdmf.common.table.DynamicTable` |
| 489 |
# to a :py:class:`~pandas.DataFrame`. |
| 490 |
|
| 491 |
############################################################################### |
| 492 |
# Accessing columns |
| 493 |
# ----------------- |
| 494 |
# To access all the values in a column, use square brackets with a colon for the |
| 495 |
# row index: ``table[:, col_name]``. If the column is a ragged array, a list of |
| 496 |
# list elements is returned. |
| 497 |
|
| 498 |
table[:, 'col1'] # returns [1, 2, 3, 4] |
| 499 |
table[:, 'col4'] # returns [[1, 0, -1], [0], [-1, 1], [1, -1]] |
| 500 |
|
| 501 |
############################################################################### |
| 502 |
# Accessing rows |
| 503 |
# -------------- |
| 504 |
# To access the i-th row in a :py:class:`~hdmf.common.table.DynamicTable`, returned |
| 505 |
# as a :py:class:`~pandas.DataFrame`, use the syntax ``table[i]``. Standard Python |
| 506 |
# and numpy slicing can be used for the row index. |
| 507 |
|
| 508 |
table[0] # get the 0th row of the table as a DataFrame |
| 509 |
table[:2] # get the first two rows |
| 510 |
table[0:3:2] # get rows 0 to 3 (exclusive) in steps of 2 |
| 511 |
table[3::-1] # get rows 3 to 0 in reverse order |
| 512 |
|
| 513 |
# the following are equivalent to table[0:3:2] |
| 514 |
table[slice(0, 3, 2)] |
| 515 |
table[np.s_[0:3:2]] |
| 516 |
table[[0, 2]] |
| 517 |
table[np.array([0, 2])] |
| 518 |
|
| 519 |
############################################################################### |
| 520 |
# .. note:: |
| 521 |
# |
| 522 |
# The syntax ``table[i]`` returns the i-th row, NOT the row with ID of `i`. |
| 523 |
|
| 524 |
############################################################################### |
| 525 |
# Iterating over rows |
| 526 |
# -------------------- |
| 527 |
# To iterate over the rows of a :py:class:`~hdmf.common.table.DynamicTable`, |
| 528 |
# first convert the :py:class:`~hdmf.common.table.DynamicTable` to a |
| 529 |
# :py:class:`~pandas.DataFrame` using |
| 530 |
# :py:meth:`DynamicTable.to_dataframe <hdmf.common.table.DynamicTable>`. |
| 531 |
# For more information on iterating over a :py:class:`~pandas.DataFrame`, |
| 532 |
# see https://pandas.pydata.org/pandas-docs/stable/user_guide/basics.html#iteration |
| 533 |
|
| 534 |
df = table.to_dataframe() |
| 535 |
for row in df.itertuples(): |
| 536 |
print(row) |
| 537 |
|
| 538 |
############################################################################### |
| 539 |
# Accessing the column data types |
| 540 |
# ------------------------------- |
| 541 |
# To access the :py:class:`~hdmf.common.table.VectorData` or |
| 542 |
# :py:class:`~hdmf.common.table.VectorIndex` object representing a column, you |
| 543 |
# can use three different methods. Use the column name in square brackets, e.g., |
| 544 |
# ``table[col_name]``, use the |
| 545 |
# :py:meth:`DynamicTable.get <hdmf.common.table.DynamicTable.get>` method, or |
| 546 |
# use the column name as an attribute, e.g., ``table.col_name``. |
| 547 |
|
| 548 |
table['col1'] |
| 549 |
table.get('col1') # equivalent to table['col1'] except this returns None if 'col1' is not found |
| 550 |
table.get('col1', default=0) # you can change the default return value |
| 551 |
table.col1 |
| 552 |
|
| 553 |
############################################################################### |
| 554 |
# .. note:: |
| 555 |
# |
| 556 |
# Using the column name as an attribute does NOT work if the column name is |
| 557 |
# the same as a non-column name attribute or method of the |
| 558 |
# :py:class:`~hdmf.common.table.DynamicTable` class, |
| 559 |
# e.g., ``name``, ``description``, ``object_id``, ``parent``, ``modified``. |
| 560 |
|
| 561 |
############################################################################### |
| 562 |
# If the column is a ragged array, then the methods above will return the |
| 563 |
# :py:class:`~hdmf.common.table.VectorIndex` associated with the ragged array. |
| 564 |
|
| 565 |
table['col4'] |
| 566 |
table.get('col4') # equivalent to table['col4'] except this returns None if 'col4' is not found |
| 567 |
table.get('col4', default=0) # you can change the default return value |
| 568 |
|
| 569 |
############################################################################### |
| 570 |
# .. note:: |
| 571 |
# |
| 572 |
# The attribute syntax ``table.col_name`` currently returns the ``VectorData`` |
| 573 |
# instead of the ``VectorIndex`` for a ragged array. This is a known |
| 574 |
# issue and will be fixed in a future version of HDMF. |
| 575 |
|
| 576 |
############################################################################### |
| 577 |
# Accessing elements from column data types |
| 578 |
# ----------------------------------------- |
| 579 |
# Standard Python and numpy slicing can be used on the |
| 580 |
# :py:class:`~hdmf.common.table.VectorData` or |
| 581 |
# :py:class:`~hdmf.common.table.VectorIndex` objects to access elements from |
| 582 |
# column data. If the column is a ragged array, then instead of a list of row |
| 583 |
# values being returned, a list of list elements for the selected rows is returned. |
| 584 |
|
| 585 |
table['col1'][0] # get the 0th element from column 'col1' |
| 586 |
table['col1'][:2] # get a list of the 0th and 1st elements |
| 587 |
table['col1'][0:3:2] # get a list of the 0th to 3rd (exclusive) elements in steps of 2 |
| 588 |
table['col1'][3::-1] # get a list of the 3rd to 0th elements in reverse order |
| 589 |
|
| 590 |
# the following are equivalent to table['col1'][0:3:2] |
| 591 |
table['col1'][slice(0, 3, 2)] |
| 592 |
table['col1'][np.s_[0:3:2]] |
| 593 |
table['col1'][[0, 2]] |
| 594 |
table['col1'][np.array([0, 2])] |
| 595 |
|
| 596 |
# this slicing and indexing works for ragged array columns as well |
| 597 |
table['col4'][:2] # get a list of the 0th and 1st list elements |
| 598 |
|
| 599 |
############################################################################### |
| 600 |
# .. note:: |
| 601 |
# |
| 602 |
# The syntax ``table[col_name][i]`` is equivalent to ``table[i, col_name]``. |
| 603 |
|
| 604 |
############################################################################### |
| 605 |
# Multi-dimensional columns |
| 606 |
# ------------------------- |
| 607 |
# A column can be represented as a multi-dimensional rectangular array or a list of lists, each containing the |
| 608 |
# same number of elements. |
| 609 |
|
| 610 |
col5 = VectorData( |
| 611 |
name='col5', |
| 612 |
description='column #5', |
| 613 |
data=[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']], |
| 614 |
) |
| 615 |
|
| 616 |
############################################################################### |
| 617 |
# Ragged multi-dimensional columns |
| 618 |
# --------------------------------- |
| 619 |
# Each element within a column can be an n-dimensional array or list or lists. |
| 620 |
# This is true for ragged array columns as well. |
| 621 |
|
| 622 |
col6 = VectorData( |
| 623 |
name='col6', |
| 624 |
description='column #6', |
| 625 |
data=[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']], |
| 626 |
) |
| 627 |
col6_ind = VectorIndex( |
| 628 |
name='col6_index', |
| 629 |
target=col6, |
| 630 |
data=[2, 3], |
| 631 |
) |
| 632 |
|
| 633 |
############################################################################### |
| 634 |
# Nested ragged array columns |
| 635 |
# --------------------------- |
| 636 |
# In the example above, the ragged array column above has two rows. The first row has two elements, |
| 637 |
# where each element has 3 sub-elements. This can be thought of as a 2x3 array. |
| 638 |
# The second row has one element with 3 sub-elements, or a 1x3 array. This |
| 639 |
# works only if the data for ``col5`` is a rectangular array, that is, each row |
| 640 |
# element contains the same number of sub-elements. If each row element does |
| 641 |
# not contain the same number of sub-elements, then a nested ragged array |
| 642 |
# approach must be used instead. |
| 643 |
# |
| 644 |
# A :py:class:`~hdmf.common.table.VectorIndex` object can index another |
| 645 |
# :py:class:`~hdmf.common.table.VectorIndex` object. For example, the first row |
| 646 |
# of a table might be a 2x3 array, the second row might be a 3x2 array, and the |
| 647 |
# third row might be a 1x1 array. This cannot be represented by a singly |
| 648 |
# indexed column, but can be represented by a nested ragged array column. |
| 649 |
|
| 650 |
col7 = VectorData( |
| 651 |
name='col7', |
| 652 |
description='column #6', |
| 653 |
data=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm'], |
| 654 |
) |
| 655 |
col7_ind = VectorIndex( |
| 656 |
name='col7_index', |
| 657 |
target=col7, |
| 658 |
data=[3, 6, 8, 10, 12, 13], |
| 659 |
) |
| 660 |
col7_ind_ind = VectorIndex( |
| 661 |
name='col7_index_index', |
| 662 |
target=col7_ind, |
| 663 |
data=[2, 5, 6], |
| 664 |
) |
| 665 |
|
| 666 |
# all indices must be added to the table |
| 667 |
table_double_ragged_col = DynamicTable( |
| 668 |
name='my table', |
| 669 |
description='an example table', |
| 670 |
columns=[col7, col7_ind, col7_ind_ind], |
| 671 |
) |
| 672 |
|
| 673 |
############################################################################### |
| 674 |
# Access the first row using the same syntax as before, except now a list of |
| 675 |
# lists is returned. You can then index the resulting list of lists to access |
| 676 |
# the individual elements. |
| 677 |
|
| 678 |
table_double_ragged_col[0, 'col7'] # returns [['a', 'b', 'c'], ['d', 'e', 'f']] |
| 679 |
table_double_ragged_col['col7'][0] # same as line above |
| 680 |
|
| 681 |
############################################################################### |
| 682 |
# Accessing the column named 'col7' using square bracket notation will return |
| 683 |
# the top-level :py:class:`~hdmf.common.table.VectorIndex` for the column. |
| 684 |
# Accessing the column named 'col7' using dot notation will return the |
| 685 |
# :py:class:`~hdmf.common.table.VectorData` object |
| 686 |
|
| 687 |
table_double_ragged_col['col7'] # returns col7_ind_ind |
| 688 |
table_double_ragged_col.col7 # returns the col7 VectorData object |
| 689 |
|
| 690 |
############################################################################### |
| 691 |
# Accessing data from a ``DynamicTable`` that contain references to rows of other ``DynamicTable`` objects |
| 692 |
# -------------------------------------------------------------------------------------------------------- |
| 693 |
# By default, when |
| 694 |
# :py:meth:`DynamicTable.__getitem__ <hdmf.common.table.DynamicTable.__getitem__>` |
| 695 |
# and :py:meth:`DynamicTable.get <hdmf.common.table.DynamicTable.get>` are supplied |
| 696 |
# with an int, list of ints, numpy array, or a slice representing rows to return, |
| 697 |
# a pandas :py:class:`~pandas.DataFrame` is returned. If the |
| 698 |
# :py:class:`~hdmf.common.table.DynamicTable` contains a |
| 699 |
# :py:class:`~hdmf.common.table.DynamicTableRegion` column that references rows |
| 700 |
# of other ``DynamicTable`` objects, then by default, the |
| 701 |
# :py:meth:`DynamicTable.__getitem__ <hdmf.common.table.DynamicTable.__getitem__>` |
| 702 |
# and :py:meth:`DynamicTable.get <hdmf.common.table.DynamicTable.get>` methods will |
| 703 |
# return row indices of the referenced table, and not the contents of the referenced |
| 704 |
# table. To return the contents of the referenced table as a nested |
| 705 |
# :py:class:`~pandas.DataFrame` containing only the referenced rows, use |
| 706 |
# :py:meth:`DynamicTable.get <hdmf.common.table.DynamicTable.get>` with ``index=False``. |
| 707 |
|
| 708 |
# create a new table of users |
| 709 |
users_table = DynamicTable( |
| 710 |
name='users', |
| 711 |
description='a table containing data/metadata about users, one user per row', |
| 712 |
) |
| 713 |
|
| 714 |
# add simple columns to this table |
| 715 |
users_table.add_column( |
| 716 |
name='first_name', |
| 717 |
description='the first name of the user', |
| 718 |
) |
| 719 |
users_table.add_column( |
| 720 |
name='last_name', |
| 721 |
description='the last name of the user', |
| 722 |
) |
| 723 |
|
| 724 |
# create a new table of addresses to reference |
| 725 |
addresses_table = DynamicTable( |
| 726 |
name='addresses', |
| 727 |
description='a table containing data/metadata about addresses, one address per row', |
| 728 |
) |
| 729 |
addresses_table.add_column( |
| 730 |
name='street_address', |
| 731 |
description='the street number and address', |
| 732 |
) |
| 733 |
addresses_table.add_column( |
| 734 |
name='city', |
| 735 |
description='the city of the address', |
| 736 |
) |
| 737 |
|
| 738 |
# add rows to the addresses table |
| 739 |
addresses_table.add_row( |
| 740 |
street_address='123 Main St', |
| 741 |
city='Springfield' |
| 742 |
) |
| 743 |
addresses_table.add_row( |
| 744 |
street_address='45 British Way', |
| 745 |
city='London' |
| 746 |
) |
| 747 |
|
| 748 |
# add a column to the users table that references rows of the addresses table |
| 749 |
users_table.add_column( |
| 750 |
name='address', |
| 751 |
description='the address of the user', |
| 752 |
table=addresses_table |
| 753 |
) |
| 754 |
|
| 755 |
# add rows to the users table |
| 756 |
users_table.add_row( |
| 757 |
first_name='Grace', |
| 758 |
last_name='Hopper', |
| 759 |
address=0 # <-- row index of the address table |
| 760 |
) |
| 761 |
|
| 762 |
users_table.add_row( |
| 763 |
first_name='Alan', |
| 764 |
last_name='Turing', |
| 765 |
address=1 # <-- row index of the address table |
| 766 |
) |
| 767 |
|
| 768 |
# get the first row of the users table |
| 769 |
users_table.get(0) |
| 770 |
|
| 771 |
############################################################################### |
| 772 |
# |
| 773 |
|
| 774 |
# get the first row of the users table with a nested dataframe |
| 775 |
users_table.get(0, index=False) |
| 776 |
|
| 777 |
############################################################################### |
| 778 |
# |
| 779 |
|
| 780 |
# get the first two rows of the users table |
| 781 |
users_table.get([0, 1]) |
| 782 |
|
| 783 |
############################################################################### |
| 784 |
# |
| 785 |
|
| 786 |
# get the first two rows of the users table with nested dataframes |
| 787 |
# of the addresses table in the address column |
| 788 |
users_table.get([0, 1], index=False) |
| 789 |
|
| 790 |
############################################################################### |
| 791 |
# .. note:: |
| 792 |
# You can also get rows from a :py:class:`~hdmf.common.table.DynamicTable` as a list of |
| 793 |
# lists where the i-th nested list contains the values for the i-th row. This method is |
| 794 |
# generally not recommended. |
| 795 |
|
| 796 |
############################################################################### |
| 797 |
# Displaying the contents of a table with references to another table |
| 798 |
# ------------------------------------------------------------------- |
| 799 |
# Earlier, we converted a :py:class:`~hdmf.common.table.DynamicTable` to a |
| 800 |
# :py:class:`~pandas.DataFrame` using |
| 801 |
# :py:meth:`DynamicTable.to_dataframe <hdmf.common.table.DynamicTable.to_dataframe>` |
| 802 |
# and printed the :py:class:`~pandas.DataFrame` to see its contents. |
| 803 |
# This also works when the :py:class:`~hdmf.common.table.DynamicTable` contains a column |
| 804 |
# that references another table. However, the entries for this column for each row |
| 805 |
# will be printed as a nested :py:class:`~pandas.DataFrame`. This can be difficult to |
| 806 |
# read, so to view only the row indices of the referenced table, pass |
| 807 |
# ``index=True`` to |
| 808 |
# :py:meth:`DynamicTable.to_dataframe <hdmf.common.table.DynamicTable.to_dataframe>`. |
| 809 |
users_df = users_table.to_dataframe(index=True) |
| 810 |
users_df |
| 811 |
|
| 812 |
############################################################################### |
| 813 |
# You can then access the referenced table using the ``table`` attribute of the |
| 814 |
# column object. This is useful when reading a table from a file where you may not have |
| 815 |
# a variable to access the referenced table. |
| 816 |
# |
| 817 |
# First, use :py:meth:`DynamicTable.__getitem__ <hdmf.common.table.DynamicTable.__getitem__>` |
| 818 |
# (square brackets notation) to get the |
| 819 |
# :py:class:`~hdmf.common.table.DynamicTableRegion` object representing the column. |
| 820 |
# Then access its ``table`` attribute to get the addresses table and convert the table |
| 821 |
# to a :py:class:`~pandas.DataFrame`. |
| 822 |
address_column = users_table['address'] |
| 823 |
read_addresses_table = address_column.table |
| 824 |
addresses_df = read_addresses_table.to_dataframe() |
| 825 |
|
| 826 |
############################################################################### |
| 827 |
# Get the addresses corresponding to the rows of the users table: |
| 828 |
address_indices = users_df['address'] # pandas Series of row indices into the addresses table |
| 829 |
addresses_df.iloc[address_indices] # use .iloc because these are row indices not ID values |
| 830 |
|
| 831 |
############################################################################### |
| 832 |
# .. note:: |
| 833 |
# The indices returned by ``users_df['address']`` are row indices and not |
| 834 |
# the ID values of the table. However, if you are using default IDs, these |
| 835 |
# values will be the same. |
| 836 |
|
| 837 |
############################################################################### |
| 838 |
# Creating custom DynamicTable subclasses |
| 839 |
# --------------------------------------- |
| 840 |
# TODO |
| 841 |
|
| 842 |
############################################################################### |
| 843 |
# Defining ``__columns__`` |
| 844 |
# ^^^^^^^^^^^^^^^^^^^^^^^^ |
| 845 |
# TODO |