Debian Codegraph @

nixio/data_frame.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # Copyright © 2019, German Neuroinformatics Node (G-Node)
3 #
4 # All rights reserved.
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted under the terms of the BSD License. See
8 # LICENSE file in the root of the Project.
9 try:
10 from collections.abc import Iterable
11 except ImportError:
12 from collections import Iterable
13 from collections import OrderedDict
14 from inspect import isclass
15 import numpy as np
16 from .exceptions import OutOfBounds
17 from .entity import Entity
18 from . import util
19 from .data_set import DataSet
20 from .datatype import DataType
21 from .section import Section
22 import csv
23
24
25 class DataFrame(Entity, DataSet):
26
27 def __init__(self, nixfile, nixparent, h5group):
28 super(DataFrame, self).__init__(nixfile, nixparent, h5group)
29 self._sources = None
30 self._columns = None
31 self._rows = None
32
33 @classmethod
34 def create_new(cls, nixfile, nixparent, h5parent, name, type_, shape, col_dtype, compression):
35 newentity = super(DataFrame, cls).create_new(nixfile, nixparent, h5parent, name, type_)
36 newentity._h5group.create_dataset("data", (shape,), col_dtype, compression)
37 return newentity
38
39 def append_column(self, column, name, datatype=None):
40 """
41 Append a new column to the DataFrame
42 In case of string, it will be better to set explicitly the datatype.
43
44 :param column: The new column
45 :type column: array-like data
46 :param name: The name of new column
47 :type name: str
48 :param datatype: The DataType of new column
49 :type datatype: nixio.DataType
50 """
51 if len(column) < len(self):
52 raise ValueError("Not enough entries for column in this dataframe")
53 elif len(column) > len(self):
54 raise ValueError("Too much entries for column in this dataframe")
55 if datatype is None:
56 datatype = DataType.get_dtype(column[0])
57 if isclass(datatype) and issubclass(datatype, str):
58 datatype = util.vlen_str_dtype
59 dt_arr = [(n, dty) for n, dty in zip(self.column_names, self.dtype)]
60 dt_arr.append((name, datatype))
61 dt = np.dtype(dt_arr)
62 column = np.array(column, dtype=datatype)
63 new_da = []
64 for i, rows in enumerate(self._h5group.group['data'][:]):
65 row_list = list(rows)
66 row_list.append(column[i])
67 row_tuple = tuple(row_list)
68 new_da.append(row_tuple)
69 farr = np.ascontiguousarray(new_da, dtype=dt)
70 del self._h5group.group['data']
71 self._h5group.group['data'] = farr
72 self._h5group.create_dataset("data", (self.shape[0],), dt)
73 self.write_direct(farr)
74
75 def append_rows(self, data):
76 """
77 Append a new row to the DataFrame. The data supplied must be iterable.
78
79 :param data: The new row
80 :type data: array-like data
81 """
82 li_data = []
83 for values in data:
84 values = tuple(values)
85 li_data.append(values)
86 pro_data = np.array(li_data, dtype=self.data_type)
87 self.append(pro_data, axis=0)
88
89 def write_column(self, column, index=None, name=None):
90 """
91 Overwrite an existing column.
92 Either index or name of the column should be provided.
93
94 :param column: The new column
95 :type column: array-like data
96 :param index: The index of the column that is written to
97 :type index: string
98 :param name: The name of the column that is written to
99 :type name: str
100 """
101 if len(column) != self.shape[0]:
102 raise ValueError('If there are missing data, please fill in None')
103 if not index and not name:
104 raise ValueError("Either index or name must not be None")
105 if name is None:
106 name = self._find_name_by_idx(index)
107 column = np.array(column)
108 for i, rows in enumerate(self._h5group.group['data'][:]):
109 cell = column[i]
110 rows[name] = cell
111 self.write_rows(rows=[rows], index=[i])
112
113 def read_columns(self, index=None, name=None, slc=None, group_by_cols=False):
114 """
115 Read one or multiple (part of) column(s) in the DataFrame
116
117 :param index: Index of column(s) to be returned
118 :type index: list of int
119 :param name: Name of column(s) to be returned
120 :type name: list of str
121 :param slc: The part of each column to be returned
122 :type slc: slice
123 :param group_by_cols: True for group return values by columns,
124 False for group by rows.
125 Only applicable for reading multiple columns
126 :type group_by_cols: bool
127 """
128 if index is None and name is None:
129 raise ValueError("Either index or name must not be None")
130 if name is None:
131 name = []
132 for col_idx in index:
133 name.append(self.column_names[col_idx])
134 if slc is None:
135 slc = np.s_[:]
136 else:
137 slc = np.s_[slc]
138 if len(name) == 1:
139 return self._read_data(slc=slc)[name[0]]
140 if group_by_cols:
141 gcol = list()
142 for col_name in name:
143 data = self._read_data(slc=slc)[col_name]
144 data = [i for i in data]
145 gcol.append(data)
146 return np.array(gcol)
147
148 return self._read_data(slc=slc)[name]
149
150 def write_rows(self, rows, index):
151 """
152 Overwrite one or multiple existing row(s)
153
154 :param rows: The new rows(s) and their data
155 :type rows: (nested) array-like data
156 :param index: Index of rows(s) to be overwritten
157 :type index: list of int
158 """
159 if not isinstance(rows[0], (Iterable, np.void)):
160 if len(index) != 1:
161 raise TypeError("Rows should be in nested form")
162 else:
163 rows = [rows]
164 if len(rows) != len(index):
165 raise IndexError(
166 "Number of rows ({}) does not match "
167 "length of indexes ({})".format(len(rows), len(index))
168 )
169 n_rows, = self.shape
170 if max(index) > (n_rows - 1):
171 raise OutOfBounds("Row index exceeds the existing number of rows")
172 if len(index) == 1:
173 rows = tuple(rows[0])
174 self._write_data(rows, slc=index)
175 else:
176 cr_list = []
177 for row in rows:
178 cr_list.append(tuple(row))
179 self._write_data(cr_list, slc=index)
180
181 def read_rows(self, index):
182 """
183 Read one or multiple row(s) in the DataFrame
184
185 :param index: Index of row(s) to be returned
186 :type index: list of int
187 """
188 return self[index]
189
190 def write_cell(self, cell, position=None, col_name=None, row_idx=None):
191 """
192 Overwrite a cell in the DataFrame
193
194 :param cell: The new cell
195 :type cell: same type as the specified column
196 :param position: Position of the targeted cell
197 :type position: tuple or list or array with length 2
198 :param col_name: The column name in which the targeted cell belongs to
199 :type col_name: str
200 :param row_idx: A length 1 list that specify on
201 which row the targeted cell is located
202 :type row_idx: list of int
203 """
204 if position is not None:
205 if len(position) != 2:
206 raise ValueError("position is invalid: "
207 "need row and column index")
208 row_idx, col_idx = position
209 targeted_row = self.read_rows(row_idx)
210 targeted_row[col_idx] = cell
211 self._write_data(targeted_row, slc=row_idx)
212 else:
213 if col_name is None or row_idx is None:
214 raise ValueError("Column and rows identifier must be given")
215 targeted_row = self.read_rows(row_idx)
216 targeted_row[col_name] = cell
217 self._write_data(targeted_row, slc=row_idx)
218
219 def read_cell(self, position=None, col_name=None, row_idx=None):
220 """
221 Read a cell in the DataFrame
222
223 :param position: Position of the targeted cell
224 :type position: tuple or list or array with length 2
225 :param col_name: The column name in which the targeted cell belongs to
226 :type col_name: str
227 :param row_idx: A length 1 list that specify on
228 which row the targeted cell is located
229 :type row_idx: list of int
230 """
231 if position is not None:
232 if len(position) != 2:
233 raise ValueError('Not a position')
234 col_idx, row_idx = position
235 return self[col_idx][row_idx]
236 else:
237 if col_name is None or row_idx is None:
238 raise ValueError("Column and rows identifier must be given")
239 cell = self[row_idx][col_name]
240 cell = cell[0]
241 return cell
242
243 def print_table(self, row_sl=None, col_sl=None):
244 """
245 Print the whole DataFrame as a table
246
247 :param row_sl: Rows to be printed; None for printing all rows
248 :type row_sl: slice or iterable of int
249
250 :param col_sl: Columns to be printed; None for printing all columns
251 :type col_sl: slice or iterable of int
252 """
253 if row_sl is None:
254 row_sl = np.s_[:]
255 if col_sl is None:
256 col_sl = np.s_[:]
257 column = np.array(self.column_names)[col_sl]
258 row_form = "{:^10}" * (len(column) + 1)
259 print(row_form.format("column:", *column))
260 if self.units is not None:
261 if None in self.units:
262 units = [u if u is not None else "" for u in self.units[col_sl]]
263 print(row_form.format(" unit:", *units))
264 if not isinstance(row_sl, Iterable):
265 ridx = list(range(len(self)))[row_sl]
266 else:
267 ridx = row_sl
268 for i, row in enumerate(self._read_data(slc=row_sl)[list(column)]):
269 print(row_form.format(" [{}]:".format(ridx[i]), *row))
270
271 def _find_idx_by_name(self, name):
272 for i, col_name in enumerate(self.column_names):
273 if col_name == name:
274 return i
275 return None
276
277 def _find_name_by_idx(self, idx):
278 if self.column_names[idx]:
279 return self.column_names[idx]
280 return None
281
282 def row_count(self):
283 """
284 Return the total number of rows
285 """
286 count = len(self)
287 return count
288
289 def write_to_csv(self, filename, mode='w'):
290 """
291 Export the whole DataFrame to a CSV file
292
293 :param filename: The resulted/ targeted CSV file to write to/ create
294 :type filename: str
295 :param mode: The column name in which the targeted cell belongs to
296 :type mode: str
297 """
298 with open(filename, mode, newline='') as csvfile:
299 if len(self.column_names) == 0:
300 # no columns? return
301 return
302 first_col_name = self.column_names[0]
303 writer = csv.DictWriter(csvfile, fieldnames=self.column_names)
304 writer.writeheader()
305 col_dict = dict()
306 for col_name in self.column_names:
307 col_name = str(col_name)
308 col_dict[col_name] = list(self[col_name])
309 complete_di_list = []
310 sample_len = len(self[first_col_name])
311 for i in range(sample_len):
312 single_sample_di = dict()
313 for col_name in self.column_names:
314 single_sample_di[col_name] = col_dict[col_name][i]
315 complete_di_list.append(single_sample_di)
316 writer.writerows(complete_di_list)
317 csvfile.close()
318
319 @property
320 def units(self):
321 """
322 The unit of the values stored in the DataFrame.
323 This is a read-write property and can be set to None.
324
325 :type: array of str
326 """
327 units = self._h5group.get_attr("units")
328 if units is None:
329 return units
330 for idx, _ in enumerate(units):
331 if units[idx] == "":
332 units[idx] = None
333 return units
334
335 @units.setter
336 def units(self, units):
337 units_arr = np.array(units, util.vlen_str_dtype)
338 for idx, unit in enumerate(units_arr):
339 if unit is not None:
340 unit = util.units.sanitizer(unit)
341 util.check_attr_type(unit, str)
342 units_arr[idx] = unit
343 else:
344 # Write None units as empty string
345 units_arr[idx] = ""
346 self._h5group.set_attr("units", units_arr)
347 if self.file.auto_update_timestamps:
348 self.force_updated_at()
349
350 @property
351 def columns(self):
352 """
353 The dtype is the list of names and data types
354 of all columns in the DatFrame.
355 This is a read only property.
356
357 :type: list of tuples
358 """
359 if np.any(self.units):
360 cols = [(n, dt, u) for n, dt, u in
361 zip(self.column_names, self.dtype, self.units)]
362 else:
363 cols = [(n, dt, None) for n, dt in
364 zip(self.column_names, self.dtype)]
365 return cols
366
367 @property
368 def column_names(self):
369 """
370 The dtype is the list of names of all columns in the DatFrame.
371 This is a read only property.
372
373 :type: list of str
374 """
375 dt = self._h5group.group["data"].dtype
376 return dt.names
377
378 @property
379 def dtype(self):
380 """
381 The dtype is the list of DataTypes of all columns in the DatFrame.
382 This is a read only property.
383
384 :type: list of DataType
385 """
386 dt = self._h5group.group["data"].dtype
387 key = self.column_names
388 col_dict = OrderedDict()
389 for k in key:
390 col_dict[k] = dt.fields[k]
391 raw_dt = col_dict.values()
392 raw_dt = list(raw_dt)
393 raw_dt_list = [ele[0] for ele in raw_dt]
394 return tuple(raw_dt_list)
395
396 @property
397 def df_shape(self):
398 """
399 The df_shape is the shape of the DataFrame
400 in (number of rows, number of columns) format.
401 This is a read only property.
402
403 :type: tuple
404 """
405 n_rows = len(self._h5group.group["data"])
406 n_cols = len(self.column_names)
407 return n_rows, n_cols
408
409 @property
410 def metadata(self):
411 """
412 Associated metadata of the entity. Sections attached to the entity via
413 this attribute can provide additional annotations. This is an optional
414 read-write property, and can be None if no metadata is available.
415
416 :type: nixio.Section
417 """
418 if "metadata" in self._h5group:
419 return Section(self.file, None,
420 self._h5group.open_group("metadata"))
421 else:
422 return None
423
424 @metadata.setter
425 def metadata(self, sect):
426 if not isinstance(sect, Section):
427 raise TypeError("{} is not of type Section".format(sect))
428 self._h5group.create_link(sect, "metadata")
429
430 @metadata.deleter
431 def metadata(self):
432 if "metadata" in self._h5group:
433 self._h5group.delete("metadata")