Debian Codegraph @

docs/gallery/plot_dynamictable_tutorial.py

raw
1 """
2
3 .. _dynamictable-tutorial:
4
5 DynamicTable Tutorial
6 =====================
7
8 This is a tutorial for interacting with :py:class:`~hdmf.common.table.DynamicTable` objects. This tutorial
9 is written for beginners and does not describe the full capabilities and nuances
10 of :py:class:`~hdmf.common.table.DynamicTable` functionality. Please see the :ref:`dynamictable-howtoguide`
11 for more complete documentation. This tutorial is designed to give
12 you basic familiarity with how :py:class:`~hdmf.common.table.DynamicTable` works and help you get started
13 with creating a :py:class:`~hdmf.common.table.DynamicTable`, adding columns and rows to a
14 :py:class:`~hdmf.common.table.DynamicTable`,
15 and accessing data in a :py:class:`~hdmf.common.table.DynamicTable`.
16
17 Introduction
18 ------------
19 The :py:class:`~hdmf.common.table.DynamicTable` class represents a column-based table
20 to which you can add custom columns. It consists of a name, a description, a list of
21 row IDs, and a list of columns.
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``.
28
29 """
30
31 # sphinx_gallery_thumbnail_path = 'figures/gallery_thumbnail_dynamictable.png'
32 from hdmf.common import DynamicTable
33
34 users_table = DynamicTable(
35 name='users',
36 description='a table containing data/metadata about users, one user per row',
37 )
38
39 ###############################################################################
40 # Adding columns
41 # --------------
42 # You can add columns to a :py:class:`~hdmf.common.table.DynamicTable` using
43 # :py:meth:`DynamicTable.add_column <hdmf.common.table.DynamicTable.add_column>`.
44
45 users_table.add_column(
46 name='first_name',
47 description='the first name of the user',
48 )
49
50 users_table.add_column(
51 name='last_name',
52 description='the last name of the user',
53 )
54
55 ###############################################################################
56 # Adding ragged array columns
57 # ---------------------------
58 # You may want to add columns to your table that have a different number of entries per row.
59 # This is called a "ragged array column". To do this, pass ``index=True`` to
60 # :py:meth:`DynamicTable.add_column <hdmf.common.table.DynamicTable.add_column>`.
61
62 users_table.add_column(
63 name='phone_number',
64 description='the phone number of the user',
65 index=True,
66 )
67
68 ###############################################################################
69 # Adding rows
70 # -----------
71 # You can add rows to a :py:class:`~hdmf.common.table.DynamicTable` using
72 # :py:meth:`DynamicTable.add_row <hdmf.common.table.DynamicTable.add_row>`.
73 # You must pass in a keyword argument for every column in the table.
74 # Ragged array column arguments should be passed in as lists or numpy arrays.
75 # The ID of the row will automatically be set and incremented for every row,
76 # starting at 0.
77
78 # id will be set to 0 automatically
79 users_table.add_row(
80 first_name='Grace',
81 last_name='Hopper',
82 phone_number=['123-456-7890'],
83 )
84
85 # id will be set to 1 automatically
86 users_table.add_row(
87 first_name='Alan',
88 last_name='Turing',
89 phone_number=['555-666-7777', '888-111-2222'],
90 )
91
92 ###############################################################################
93 # Displaying the table contents as a pandas ``DataFrame``
94 # -------------------------------------------------------
95 # `pandas`_ is a popular data analysis tool for working with tabular data.
96 # Convert your :py:class:`~hdmf.common.table.DynamicTable` to a pandas
97 # :py:class:`~pandas.DataFrame` using
98 # :py:meth:`DynamicTable.to_dataframe <hdmf.common.table.DynamicTable.to_dataframe>`.
99 #
100 # .. _pandas: https://pandas.pydata.org/
101
102 users_df = users_table.to_dataframe()
103 users_df
104
105 ###############################################################################
106 # Accessing the table as a :py:class:`~pandas.DataFrame` provides you with powerful
107 # methods for indexing, selecting, and querying tabular data from `pandas`_.
108
109 ###############################################################################
110 # Get the "last_name" column as a pandas :py:class:`~pandas.Series`:
111 users_df['last_name']
112
113 ###############################################################################
114 # The index of the :py:class:`~pandas.DataFrame` is automatically set to the
115 # table IDs. Get the row with ID = 0 as a pandas :py:class:`~pandas.Series`:
116 users_df.loc[0]
117
118 ###############################################################################
119 # Get single cells of the table by indexing with both ID and column name:
120 print('My first user:', users_df.loc[0, 'first_name'], users_df.loc[0, 'last_name'])
121
122 ###############################################################################
123 # Adding columns that reference rows of other ``DynamicTable`` objects
124 # --------------------------------------------------------------------
125 # You can create a column that references rows of another
126 # :py:class:`~hdmf.common.table.DynamicTable`. This is analogous to
127 # a foreign key in a relational database. To do this, use the ``table`` keyword
128 # argument for
129 # :py:meth:`DynamicTable.add_column <hdmf.common.table.DynamicTable.add_column>`
130 # and set it to the other table.
131
132 # create a new table of users
133 users_table = DynamicTable(
134 name='users',
135 description='a table containing data/metadata about users, one user per row',
136 )
137
138 # add simple columns to this table
139 users_table.add_column(
140 name='first_name',
141 description='the first name of the user',
142 )
143 users_table.add_column(
144 name='last_name',
145 description='the last name of the user',
146 )
147
148 # create a new table of addresses to reference
149 addresses_table = DynamicTable(
150 name='addresses',
151 description='a table containing data/metadata about addresses, one address per row',
152 )
153 addresses_table.add_column(
154 name='street_address',
155 description='the street number and address',
156 )
157 addresses_table.add_column(
158 name='city',
159 description='the city of the address',
160 )
161
162 # add rows to the addresses table
163 addresses_table.add_row(
164 street_address='123 Main St',
165 city='Springfield'
166 )
167 addresses_table.add_row(
168 street_address='45 British Way',
169 city='London'
170 )
171
172 # add a column to the users table that references rows of the addresses table
173 users_table.add_column(
174 name='address',
175 description='the address of the user',
176 table=addresses_table
177 )
178
179 # add rows to the users table
180 users_table.add_row(
181 first_name='Grace',
182 last_name='Hopper',
183 address=0 # <-- row index of the address table
184 )
185
186 users_table.add_row(
187 first_name='Alan',
188 last_name='Turing',
189 address=1 # <-- row index of the address table
190 )
191
192 ###############################################################################
193 # Displaying the contents of a table with references to another table
194 # -------------------------------------------------------------------
195 # Earlier, we converted a :py:class:`~hdmf.common.table.DynamicTable` to a
196 # :py:class:`~pandas.DataFrame` using
197 # :py:meth:`DynamicTable.to_dataframe <hdmf.common.table.DynamicTable.to_dataframe>`
198 # and printed the :py:class:`~pandas.DataFrame` to see its contents.
199 # This also works when the :py:class:`~hdmf.common.table.DynamicTable` contains a column
200 # that references another table. However, the entries for this column for each row
201 # will be printed as a nested :py:class:`~pandas.DataFrame`. This can be difficult to
202 # read, so to view only the row indices of the referenced table, pass
203 # ``index=True`` to
204 # :py:meth:`DynamicTable.to_dataframe <hdmf.common.table.DynamicTable.to_dataframe>`.
205 users_df = users_table.to_dataframe(index=True)
206 users_df
207
208 ###############################################################################
209 # You can then access the referenced table using the ``table`` attribute of the
210 # column object. This is useful when reading a table from a file where you may not have
211 # a variable to access the referenced table.
212 #
213 # First, use :py:meth:`DynamicTable.__getitem__ <hdmf.common.table.DynamicTable.__getitem__>`
214 # (square brackets notation) to get the
215 # :py:class:`~hdmf.common.table.DynamicTableRegion` object representing the column.
216 # Then access its ``table`` attribute to get the addresses table and convert the table
217 # to a :py:class:`~pandas.DataFrame`.
218 address_column = users_table['address']
219 read_addresses_table = address_column.table
220 addresses_df = read_addresses_table.to_dataframe()
221
222 ###############################################################################
223 # Get the addresses corresponding to the rows of the users table:
224 address_indices = users_df['address'] # pandas Series of row indices into the addresses table
225 addresses_df.iloc[address_indices] # use .iloc because these are row indices not ID values
226
227 ###############################################################################
228 # .. note::
229 # The indices returned by ``users_df['address']`` are row indices and not
230 # the ID values of the table. However, if you are using default IDs, these
231 # values will be the same.
232
233 ###############################################################################
234 # You now know the basics of creating :py:class:`~hdmf.common.table.DynamicTable`
235 # objects and reading data from them, including tables that have ragged array columns
236 # and references to other tables. Learn more about working with
237 # :py:class:`~hdmf.common.table.DynamicTable` in the :ref:`dynamictable-howtoguide`,
238 # including:
239 #
240 # * ragged array columns with references to other tables
241 # * nested ragged array columns
242 # * columns with multidimensional array data
243 # * columns with enumerated (categorical) data
244 # * accessing data and properties from the column objects directly
245 # * writing and reading tables to a file
246 # * writing expandable tables
247 # * defining subclasses of :py:class:`~hdmf.common.table.DynamicTable`