Skip to content

named_array

Named arrays with typed, named columns backed by array.array and numpy.

This module provides :class:Field and :class:NamedArray for managing columnar data with named fields, type formats, and efficient conversion to numpy arrays and pandas DataFrames.

Example
narr = named_array.NamedArray('id=i,val=f')
narr.append(1, 10.0)  # Append one row.
narr.data()['id']  # The per-field numpy arrays.
narr.to_numpy()  # A 2D array - numeric, size==1 fields only.

Field

Represents a single typed column within a NamedArray.

Attributes:

Name Type Description
name

The column name.

data

The underlying storage (array.array or list).

size

Number of elements per row (1 for scalar, >1 for fixed vectors).

fmt

The data format character code.

str_tbl

String table used for string columns ('S' format).

Source code in py_misc_utils/named_array.py
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
class Field:
  """Represents a single typed column within a NamedArray.

  Attributes:
    name: The column name.
    data: The underlying storage (array.array or list).
    size: Number of elements per row (1 for scalar, >1 for fixed vectors).
    fmt: The data format character code.
    str_tbl: String table used for string columns ('S' format).
  """
  __slots__ = ('data', 'fmt', 'name', 'size', 'str_tbl')

  def __init__(self, name, data, size, fmt, str_tbl):
    """Initialize a Field with name, data storage, size, format, and string table.

    Args:
      name: The column name.
      data: The underlying storage (array.array or list).
      size: Number of elements per row.
      fmt: The data format character code.
      str_tbl: String table used for string columns.
    """
    self.name = name
    self.data = data
    self.size = size
    self.fmt = fmt
    self.str_tbl = str_tbl

  def np_array(self):
    """Return the field's data as a numpy array.

    Returns:
      A numpy array of shape (n,) if size==1, or (n, size) otherwise.
    """
    arr = np.array(self.data)

    return arr.reshape(-1, self.size) if self.size > 1 else arr

  def append(self, arg):
    """Append a single value to the field's data.

    Args:
      arg: The value to append. For string fields ('S' format), it is
        interned via the string table.
    """
    if self.fmt == 'S':
      arg = self.stringify(arg)

    if self.size == 1:
      self.data.append(arg)
    else:
      assert self.size == len(arg), f'{self.name}({self.size}) vs. {len(arg)}'
      self.data.extend(arg)

  def extend(self, arg):
    """Extend the field's data with multiple values.

    Args:
      arg: An iterable of values to append. Its length must be a multiple
        of self.size. String fields are interned via the string table.
    """
    assert len(arg) % self.size == 0, f'{self.name}({self.size}) vs. {len(arg)}'
    if self.fmt == 'S':
      arg = [self.str_tbl.add(x) for x in arg]

    if isinstance(arg, np.ndarray) and isinstance(self.data, array.array):
      nptype = np.dtype(self.data.typecode)
      if nptype != arg.dtype:
        arg = arg.astype(nptype)
      self.data.frombytes(arg.tobytes())
    else:
      self.data.extend(arg)

  def stringify(self, arg):
    """Intern string values through the string table.

    Args:
      arg: A string or tuple of strings to intern.

    Returns:
      The interned string (or tuple of interned strings).
    """
    if self.size == 1:
      return self.str_tbl.add(arg)

    return tuple(self.str_tbl.add(x) for x in arg)

  def __len__(self):
    """Return the number of rows of the field."""
    return len(self.data) // self.size

  def __getitem__(self, i):
    """Return the value of a row of the field.

    Args:
      i: The row index, or a slice of row indices.

    Returns:
      The row value - the element for size==1 fields, the list of the
      size elements otherwise. A slice of a vector field returns a list
      of per-row lists.
    """
    if self.size == 1:
      return self.data[i]
    elif isinstance(i, int):
      offset = i * self.size

      return self.data[offset:offset + self.size]
    else:
      start, stop, step = (x * self.size for x in i.indices(len(self)))
      data = []
      for n in range(start, stop, step):
        data.append(self.data[n:n + self.size])

      return data

  @staticmethod
  def create(name, fmt, str_tbl):
    """Create a Field from a name and a format specification.

    Args:
      name: The column name.
      fmt: Format specification, optionally holding a size prefix (e.g.
        '3f' = 3 float32 per row); non-numeric formats ('S', 'x') fall
        back to a plain list storage.
      str_tbl: String table used for string columns.

    Returns:
      The created Field.
    """
    m = re.match(r'(\d+)([a-zA-Z])', fmt)
    if m:
      size, efmt = int(m.group(1)), m.group(2)
    else:
      size, efmt = 1, fmt

    data = array.array(efmt) if not efmt in _NOT_NUMERIC else []

    return Field(name, data, size, efmt, str_tbl)

np_array()

Return the field's data as a numpy array.

Returns:

Type Description

A numpy array of shape (n,) if size==1, or (n, size) otherwise.

Source code in py_misc_utils/named_array.py
55
56
57
58
59
60
61
62
63
def np_array(self):
  """Return the field's data as a numpy array.

  Returns:
    A numpy array of shape (n,) if size==1, or (n, size) otherwise.
  """
  arr = np.array(self.data)

  return arr.reshape(-1, self.size) if self.size > 1 else arr

append(arg)

Append a single value to the field's data.

Parameters:

Name Type Description Default
arg

The value to append. For string fields ('S' format), it is interned via the string table.

required
Source code in py_misc_utils/named_array.py
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
def append(self, arg):
  """Append a single value to the field's data.

  Args:
    arg: The value to append. For string fields ('S' format), it is
      interned via the string table.
  """
  if self.fmt == 'S':
    arg = self.stringify(arg)

  if self.size == 1:
    self.data.append(arg)
  else:
    assert self.size == len(arg), f'{self.name}({self.size}) vs. {len(arg)}'
    self.data.extend(arg)

extend(arg)

Extend the field's data with multiple values.

Parameters:

Name Type Description Default
arg

An iterable of values to append. Its length must be a multiple of self.size. String fields are interned via the string table.

required
Source code in py_misc_utils/named_array.py
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
def extend(self, arg):
  """Extend the field's data with multiple values.

  Args:
    arg: An iterable of values to append. Its length must be a multiple
      of self.size. String fields are interned via the string table.
  """
  assert len(arg) % self.size == 0, f'{self.name}({self.size}) vs. {len(arg)}'
  if self.fmt == 'S':
    arg = [self.str_tbl.add(x) for x in arg]

  if isinstance(arg, np.ndarray) and isinstance(self.data, array.array):
    nptype = np.dtype(self.data.typecode)
    if nptype != arg.dtype:
      arg = arg.astype(nptype)
    self.data.frombytes(arg.tobytes())
  else:
    self.data.extend(arg)

stringify(arg)

Intern string values through the string table.

Parameters:

Name Type Description Default
arg

A string or tuple of strings to intern.

required

Returns:

Type Description

The interned string (or tuple of interned strings).

Source code in py_misc_utils/named_array.py
100
101
102
103
104
105
106
107
108
109
110
111
112
def stringify(self, arg):
  """Intern string values through the string table.

  Args:
    arg: A string or tuple of strings to intern.

  Returns:
    The interned string (or tuple of interned strings).
  """
  if self.size == 1:
    return self.str_tbl.add(arg)

  return tuple(self.str_tbl.add(x) for x in arg)

create(name, fmt, str_tbl) staticmethod

Create a Field from a name and a format specification.

Parameters:

Name Type Description Default
name

The column name.

required
fmt

Format specification, optionally holding a size prefix (e.g. '3f' = 3 float32 per row); non-numeric formats ('S', 'x') fall back to a plain list storage.

required
str_tbl

String table used for string columns.

required

Returns:

Type Description

The created Field.

Source code in py_misc_utils/named_array.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
@staticmethod
def create(name, fmt, str_tbl):
  """Create a Field from a name and a format specification.

  Args:
    name: The column name.
    fmt: Format specification, optionally holding a size prefix (e.g.
      '3f' = 3 float32 per row); non-numeric formats ('S', 'x') fall
      back to a plain list storage.
    str_tbl: String table used for string columns.

  Returns:
    The created Field.
  """
  m = re.match(r'(\d+)([a-zA-Z])', fmt)
  if m:
    size, efmt = int(m.group(1)), m.group(2)
  else:
    size, efmt = 1, fmt

  data = array.array(efmt) if not efmt in _NOT_NUMERIC else []

  return Field(name, data, size, efmt, str_tbl)

NamedArray

A columnar data container with named, typed fields.

Fields are defined by name=format pairs - comma-separated, e.g. 'id=i,name=S' - where the format is an array.array type code, optionally prefixed with a fixed vector size (e.g. '3f' for a 3-elements float vector per row). String fields use the 'S' code, whose values are interned in a per-array string table.

Supports appending rows, extending from other NamedArrays, conversion to numpy arrays and pandas DataFrames.

Example
narr = named_array.NamedArray('id=i,val=f,name=S')
narr.append(1, 10.0, 'alice')
narr.kwappend(id=2, val=20.0, name='bob')
narr.shape  # (2, 3) - rows and fields.
narr[0]  # (1, 10.0, 'alice') - a whole row as a tuple.
Source code in py_misc_utils/named_array.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
class NamedArray:
  """A columnar data container with named, typed fields.

  Fields are defined by name=format pairs - comma-separated, e.g.
  'id=i,name=S' - where the format is an array.array type code, optionally
  prefixed with a fixed vector size (e.g. '3f' for a 3-elements float
  vector per row). String fields use the 'S' code, whose values are
  interned in a per-array string table.

  Supports appending rows, extending from other NamedArrays, conversion to
  numpy arrays and pandas DataFrames.

  Example:
    narr = named_array.NamedArray('id=i,val=f,name=S')
    narr.append(1, 10.0, 'alice')
    narr.kwappend(id=2, val=20.0, name='bob')
    narr.shape  # (2, 3) - rows and fields.
    narr[0]  # (1, 10.0, 'alice') - a whole row as a tuple.
  """

  def __init__(self, names, fmt=None):
    """Initialize a NamedArray with named fields.

    Args:
      names: Either a comma-separated string of 'name=format' pairs, or a
        sequence of field names.
      fmt: When provided, names is treated as a plain sequence of names
        and fmt holds the matching format codes - either as a single
        space-separated string or as a sequence of format strings.

    Example:
      named_array.NamedArray('id=i,val=S')  # Pairs in one string.
      named_array.NamedArray(['id', 'val'], 'iS')  # Names + fmt string.
      named_array.NamedArray(['id', 'val'], ['i', 'S'])  # Per-field fmts.
    """
    fnames = re.split(r'\s*,\s*', names) if isinstance(names, str) else names
    if fmt is None:
      cnames, ffmt = [], []
      for name_format in fnames:
        m = re.match(r'(\w+)\s*=\s*(\w+)$', name_format)
        tas.check(m, msg=f'Invalid name=format specification: {name_format}')
        cnames.append(m.group(1))
        ffmt.append(m.group(2))

      fnames = cnames
    else:
      ffmt = re.findall(r'\d*[a-zA-Z]', fmt) if isinstance(fmt, str) else fmt
      tas.check_eq(len(fnames),
                   len(ffmt),
                   msg=f'Mismatching names and format sizes: {fnames} vs {ffmt}')

    str_tbl = cu.StringTable()
    fields = dict()
    for name, cfmt in zip(fnames, ffmt):
      fields[name] = Field.create(name, cfmt, str_tbl)

    self._fields = fields
    self._fieldseq = tuple(fields.values())
    self._str_tbl = str_tbl

  def add_column(self, name, fmt, data):
    """Add a new column to the NamedArray.

    Args:
      name: The column name (must not already exist).
      fmt: The format character code for the column.
      data: The column data (list, array, or numpy array).
    """
    tas.check(name not in self._fields, msg=f'Column "{name}" already exists')

    field = Field.create(name, fmt, self._str_tbl)

    if isinstance(data, np.ndarray):
      data = data.flatten()

    field.extend(data)

    self._fields[name] = field
    self._fieldseq += (field,)

  def append(self, *args):
    """Append a row of values to each field.

    Args:
      *args: One value per field, in field order. Vector fields take a
        sequence of self.size values.

    Example:
      narr = named_array.NamedArray('id=i,name=S')
      narr.append(1, 'alice')  # One full row.
    """
    for field, arg in zip(self._fieldseq, args):
      field.append(arg)

  def extend(self, other):
    """Extend this NamedArray with rows from another NamedArray.

    Args:
      other: Another NamedArray with the same fields.
    """
    for field, ofield in zip(self._fieldseq, other._fieldseq):
      field.extend(ofield.data)

  def append_extend(self, *args):
    """Extend each field with iterables of values.

    Args:
      *args: One iterable per field, in field order.
    """
    for field, arg in zip(self._fieldseq, args):
      field.extend(arg)

  def kwappend(self, **kwargs):
    """Append a row using keyword arguments keyed by field name.

    Args:
      **kwargs: Field name to value mappings.
    """
    for name, field in self._fields.items():
      arg = kwargs[name]
      field.append(arg)

  def get_tuple_item(self, i):
    """Return the i-th row as a tuple of field values.

    Args:
      i: The row index.

    Returns:
      A tuple of values, one per field. Alias of __getitem__.
    """
    item = []
    for field in self._fieldseq:
      item.append(field[i])

    return tuple(item)

  def get_arrays(self, names=None):
    """Return numpy arrays for the specified fields, or all fields.

    Args:
      names: Optional collection of field names. If None, all fields are returned.

    Returns:
      A tuple of numpy arrays, one per requested field - shaped (n,) for
      scalar fields and (n, size) for vector fields.
    """
    if names:
      return tuple(self._fields[name].np_array() for name in names)

    return tuple(field.np_array() for field in self._fieldseq)

  def get_array(self, name):
    """Return the numpy array for a single field.

    Args:
      name: The field name.

    Returns:
      A numpy array containing the field's data.
    """
    return self._fields[name].np_array()

  def data(self):
    """Return a mapping of field name to its numpy array data.

    Returns:
      A dict mapping field names to their numpy arrays.
    """
    return {field.name: field.np_array() for field in self._fieldseq}

  def to_numpy(self, dtype=None):
    """Convert all fields to a single 2D numpy array.

    All fields must be numeric with size==1 - string ('S') and vector
    fields cannot be converted.

    Args:
      dtype: Optional numpy dtype. If None, inferred from field dtypes.

    Returns:
      A numpy array of shape (n_rows, n_fields).
    """
    for field in self._fieldseq:
      tas.check(field.fmt not in _NOT_NUMERIC,
                msg=f'Only purely numeric arrays can be converted to ' \
                f'numpy: {field.name}={field.fmt}')
      tas.check_eq(field.size, 1,
                   msg=f'Only fields with size==1 can be converted to ' \
                   f'numpy: {field.name}={field.size}')

    if dtype is None:
      dtype = npu.infer_np_dtype(self.dtypes())

    na = np.empty(self.shape, dtype=dtype)
    for i, field in enumerate(self._fieldseq):
      na[:, i] = field.data

    return na

  def __len__(self):
    """Return the number of rows in the NamedArray.

    Returns:
      The row count, or 0 if there are no fields.
    """
    size = None
    for field in self._fieldseq:
      fsize = len(field)
      if size is None:
        size = fsize
      else:
        tas.check_eq(fsize,
                     size,
                     msg=f'Unmatching size for "{field.name}": {fsize} vs. {size}')

    return size or 0

  def __getitem__(self, i):
    """Return the i-th row as a dict of field values.

    Args:
      i: The row index.

    Returns:
      A dict mapping each field name to the row value.
    """
    item = dict()
    for field in self._fieldseq:
      item[field.name] = field[i]

    return item

  def __array__(self, dtype=None):
    """Return the numeric contents as a numpy array.

    Args:
      dtype: Optional numpy dtype of the array.

    Returns:
      The 2D numpy array of the fields, as per to_numpy().
    """
    return self.to_numpy(dtype=dtype)

  def to_dataframe(self):
    """Convert the NamedArray into a pandas DataFrame.

    Returns:
      A DataFrame with one column per field, holding the numpy arrays of
      the scalar fields and the lists of the vector fields.

    Example:
      narr = named_array.NamedArray('id=i,name=S')
      narr.append(1, 'alice')
      narr.to_dataframe().to_dict('list')  # {'id': [1], 'name': ['alice']}
    """
    df_data = dict()
    for name, arr in self.data().items():
      df_data[name] = arr if arr.ndim == 1 else arr.tolist()

    return pd.DataFrame(data=df_data)

  @property
  def shape(self):
    """Return the (rows, columns) shape of the array.

    Returns:
      A tuple with the number of rows and the number of fields.
    """
    return (len(self), len(self._fieldseq))

  def dtypes(self):
    """Return the numpy dtypes of the fields.

    Returns:
      A tuple with one numpy dtype per field: non-numeric fields get
      dtype('O').
    """
    types = []
    for field in self._fieldseq:
      types.append(np.dtype('O') if field.fmt in _NOT_NUMERIC else np.dtype(field.fmt))

    return tuple(types)

shape property

Return the (rows, columns) shape of the array.

Returns:

Type Description

A tuple with the number of rows and the number of fields.

add_column(name, fmt, data)

Add a new column to the NamedArray.

Parameters:

Name Type Description Default
name

The column name (must not already exist).

required
fmt

The format character code for the column.

required
data

The column data (list, array, or numpy array).

required
Source code in py_misc_utils/named_array.py
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
def add_column(self, name, fmt, data):
  """Add a new column to the NamedArray.

  Args:
    name: The column name (must not already exist).
    fmt: The format character code for the column.
    data: The column data (list, array, or numpy array).
  """
  tas.check(name not in self._fields, msg=f'Column "{name}" already exists')

  field = Field.create(name, fmt, self._str_tbl)

  if isinstance(data, np.ndarray):
    data = data.flatten()

  field.extend(data)

  self._fields[name] = field
  self._fieldseq += (field,)

append(*args)

Append a row of values to each field.

Parameters:

Name Type Description Default
*args

One value per field, in field order. Vector fields take a sequence of self.size values.

()
Example
narr = named_array.NamedArray('id=i,name=S')
narr.append(1, 'alice')  # One full row.
Source code in py_misc_utils/named_array.py
248
249
250
251
252
253
254
255
256
257
258
259
260
def append(self, *args):
  """Append a row of values to each field.

  Args:
    *args: One value per field, in field order. Vector fields take a
      sequence of self.size values.

  Example:
    narr = named_array.NamedArray('id=i,name=S')
    narr.append(1, 'alice')  # One full row.
  """
  for field, arg in zip(self._fieldseq, args):
    field.append(arg)

extend(other)

Extend this NamedArray with rows from another NamedArray.

Parameters:

Name Type Description Default
other

Another NamedArray with the same fields.

required
Source code in py_misc_utils/named_array.py
262
263
264
265
266
267
268
269
def extend(self, other):
  """Extend this NamedArray with rows from another NamedArray.

  Args:
    other: Another NamedArray with the same fields.
  """
  for field, ofield in zip(self._fieldseq, other._fieldseq):
    field.extend(ofield.data)

append_extend(*args)

Extend each field with iterables of values.

Parameters:

Name Type Description Default
*args

One iterable per field, in field order.

()
Source code in py_misc_utils/named_array.py
271
272
273
274
275
276
277
278
def append_extend(self, *args):
  """Extend each field with iterables of values.

  Args:
    *args: One iterable per field, in field order.
  """
  for field, arg in zip(self._fieldseq, args):
    field.extend(arg)

kwappend(**kwargs)

Append a row using keyword arguments keyed by field name.

Parameters:

Name Type Description Default
**kwargs

Field name to value mappings.

{}
Source code in py_misc_utils/named_array.py
280
281
282
283
284
285
286
287
288
def kwappend(self, **kwargs):
  """Append a row using keyword arguments keyed by field name.

  Args:
    **kwargs: Field name to value mappings.
  """
  for name, field in self._fields.items():
    arg = kwargs[name]
    field.append(arg)

get_tuple_item(i)

Return the i-th row as a tuple of field values.

Parameters:

Name Type Description Default
i

The row index.

required

Returns:

Type Description

A tuple of values, one per field. Alias of getitem.

Source code in py_misc_utils/named_array.py
290
291
292
293
294
295
296
297
298
299
300
301
302
303
def get_tuple_item(self, i):
  """Return the i-th row as a tuple of field values.

  Args:
    i: The row index.

  Returns:
    A tuple of values, one per field. Alias of __getitem__.
  """
  item = []
  for field in self._fieldseq:
    item.append(field[i])

  return tuple(item)

get_arrays(names=None)

Return numpy arrays for the specified fields, or all fields.

Parameters:

Name Type Description Default
names

Optional collection of field names. If None, all fields are returned.

None

Returns:

Type Description

A tuple of numpy arrays, one per requested field - shaped (n,) for

scalar fields and (n, size) for vector fields.

Source code in py_misc_utils/named_array.py
305
306
307
308
309
310
311
312
313
314
315
316
317
318
def get_arrays(self, names=None):
  """Return numpy arrays for the specified fields, or all fields.

  Args:
    names: Optional collection of field names. If None, all fields are returned.

  Returns:
    A tuple of numpy arrays, one per requested field - shaped (n,) for
    scalar fields and (n, size) for vector fields.
  """
  if names:
    return tuple(self._fields[name].np_array() for name in names)

  return tuple(field.np_array() for field in self._fieldseq)

get_array(name)

Return the numpy array for a single field.

Parameters:

Name Type Description Default
name

The field name.

required

Returns:

Type Description

A numpy array containing the field's data.

Source code in py_misc_utils/named_array.py
320
321
322
323
324
325
326
327
328
329
def get_array(self, name):
  """Return the numpy array for a single field.

  Args:
    name: The field name.

  Returns:
    A numpy array containing the field's data.
  """
  return self._fields[name].np_array()

data()

Return a mapping of field name to its numpy array data.

Returns:

Type Description

A dict mapping field names to their numpy arrays.

Source code in py_misc_utils/named_array.py
331
332
333
334
335
336
337
def data(self):
  """Return a mapping of field name to its numpy array data.

  Returns:
    A dict mapping field names to their numpy arrays.
  """
  return {field.name: field.np_array() for field in self._fieldseq}

to_numpy(dtype=None)

Convert all fields to a single 2D numpy array.

All fields must be numeric with size==1 - string ('S') and vector fields cannot be converted.

Parameters:

Name Type Description Default
dtype

Optional numpy dtype. If None, inferred from field dtypes.

None

Returns:

Type Description

A numpy array of shape (n_rows, n_fields).

Source code in py_misc_utils/named_array.py
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
def to_numpy(self, dtype=None):
  """Convert all fields to a single 2D numpy array.

  All fields must be numeric with size==1 - string ('S') and vector
  fields cannot be converted.

  Args:
    dtype: Optional numpy dtype. If None, inferred from field dtypes.

  Returns:
    A numpy array of shape (n_rows, n_fields).
  """
  for field in self._fieldseq:
    tas.check(field.fmt not in _NOT_NUMERIC,
              msg=f'Only purely numeric arrays can be converted to ' \
              f'numpy: {field.name}={field.fmt}')
    tas.check_eq(field.size, 1,
                 msg=f'Only fields with size==1 can be converted to ' \
                 f'numpy: {field.name}={field.size}')

  if dtype is None:
    dtype = npu.infer_np_dtype(self.dtypes())

  na = np.empty(self.shape, dtype=dtype)
  for i, field in enumerate(self._fieldseq):
    na[:, i] = field.data

  return na

to_dataframe()

Convert the NamedArray into a pandas DataFrame.

Returns:

Type Description

A DataFrame with one column per field, holding the numpy arrays of

the scalar fields and the lists of the vector fields.

Example
narr = named_array.NamedArray('id=i,name=S')
narr.append(1, 'alice')
narr.to_dataframe().to_dict('list')  # {'id': [1], 'name': ['alice']}
Source code in py_misc_utils/named_array.py
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
def to_dataframe(self):
  """Convert the NamedArray into a pandas DataFrame.

  Returns:
    A DataFrame with one column per field, holding the numpy arrays of
    the scalar fields and the lists of the vector fields.

  Example:
    narr = named_array.NamedArray('id=i,name=S')
    narr.append(1, 'alice')
    narr.to_dataframe().to_dict('list')  # {'id': [1], 'name': ['alice']}
  """
  df_data = dict()
  for name, arr in self.data().items():
    df_data[name] = arr if arr.ndim == 1 else arr.tolist()

  return pd.DataFrame(data=df_data)

dtypes()

Return the numpy dtypes of the fields.

Returns:

Type Description

A tuple with one numpy dtype per field: non-numeric fields get

dtype('O').

Source code in py_misc_utils/named_array.py
439
440
441
442
443
444
445
446
447
448
449
450
def dtypes(self):
  """Return the numpy dtypes of the fields.

  Returns:
    A tuple with one numpy dtype per field: non-numeric fields get
    dtype('O').
  """
  types = []
  for field in self._fieldseq:
    types.append(np.dtype('O') if field.fmt in _NOT_NUMERIC else np.dtype(field.fmt))

  return tuple(types)