Skip to content

Modifying

Adding, changing, removing and reordering records and columns.

Appending

append

append(
    data_item=None,
    respect_kd=False,
    *,
    lol=None,
    la=None,
    fast=False,
)

Add one row, or several, to the end of the Daf.

This is the general way to add data. Give it one of these:

  • A dict, or a KeyedList: one row, placed by column name, in any order. A missing key gets NULL, the empty string. A key that is not a column is dropped.
  • A list of values: one row, in column order. A short list is padded with NULL. A longer one raises ValueError.
  • A list of dicts: several rows, as extend() adds them.
  • A Daf with the same columns: its rows, as concat() adds them.
  • lol=, a list of lists: several rows, each in column order.
  • la=, a list: one row, even when its values are lists. Use it to say so plainly.

None, an empty dict, an empty list and an empty Daf add nothing. append() changes this Daf and returns it, so calls can be chained.

Keys. The keyfield is not checked, so a key that is already there is added again, as a second row. This keeps appending fast. With respect_kd=True, the row that has the same key is replaced instead. That looks the key up on every call, so it costs more for many single rows.

Copies. With columns defined, each row is copied, so you can change or reuse your list or dict afterwards. With no columns defined, a list is added as it is.

fast=True adds the row with no copy, and checks it only lightly, for speed in a loop that builds each row itself:

  • A KeyedList must share this Daf's column names, as one from default_record(astype=KeyedList), iloc() or iter_klist() does. Nothing else is checked.
  • A dict or list is checked fully if it is the first row of an empty Daf. A dict must have the columns as its keys, in order, and a list one value for each column. Every later dict or list is checked only for its number of values. A row that fails raises ValueError.
  • The list, or the KeyedList's values, becomes the row itself. Do not change it afterwards, and do not fill one list in place and append it again: every row would be that same list.
  • A later dict in another order, with the right number of values, puts its values in the wrong columns. Leave out fast if rows may come in another order.

fast makes no difference to the first row of a Daf with no columns, to a Daf, to a list of dicts, or with respect_kd=True and a keyfield.

Parameters:

Name Type Description Default
data_item 'Daf' | T_loda | T_da | T_la | KeyedList | None

The row or rows to add.

None
respect_kd bool

If True, replace the row that has the same key. If False, the default, add it.

False
lol T_lola | None

Several rows, each a list of values in column order.

None
la T_la | None

One row, as a list of values in column order. Its items are not read as rows.

None
fast bool

If True, add the row with no copy. Check the first row of an empty Daf fully, and every row's length. See above.

False

Returns:

Type Description
'Daf'

This Daf, which has been changed.

Raises:

Type Description
TypeError

More than one of data_item, lol and la is given, or data_item is not a supported type.

ValueError

A list has more values than there are columns.

KeyError

data_item is a Daf whose columns differ, in name or in order. Nothing is added.

Examples:

The table used in the examples:

>>> daf = Daf(cols=['id', 'item', 'qty'], keyfield='id')

Each call is followed by a read of the row it added. append() returns the Daf, so at the prompt a bare call shows the whole table.

A dict, by column name. A missing column gets NULL, and an unknown key is dropped:

>>> daf.append({'qty': 3, 'id': 'a1', 'item': 'pen'})

| id | item | qty |
| -: | ---: | --: |
| a1 |  pen |   3 |

%% daf rows=1; cols=3; keyfield='id'; name=''

>>> daf.append({'id': 'b2', 'color': 'red'})

| id | item | qty |
| -: | ---: | --: |
| a1 |  pen |   3 |
| b2 |      |     |

%% daf rows=2; cols=3; keyfield='id'; name=''

A list, in column order. A short list is padded, and a long one raises:

>>> daf.append(['c3', 'pad', 7])

| id | item | qty |
| -: | ---: | --: |
| a1 |  pen |   3 |
| b2 |      |     |
| c3 |  pad |   7 |

%% daf rows=3; cols=3; keyfield='id'; name=''

>>> daf.append(['d4'])

| id | item | qty |
| -: | ---: | --: |
| a1 |  pen |   3 |
| b2 |      |     |
| c3 |  pad |   7 |
| d4 |      |     |

%% daf rows=4; cols=3; keyfield='id'; name=''

>>> daf.append(['e5', 'tag', 1, 'extra'])
Traceback (most recent call last):
...
ValueError: append(): the list has 4 values for 3 columns.

Several rows: a list of dicts, lol=, or another Daf with the same columns:

>>> daf.append([{'id': 'f6', 'qty': 2}, {'id': 'g7', 'qty': 5}])

| id | item | qty |
| -: | ---: | --: |
| a1 |  pen |   3 |
| b2 |      |     |
| c3 |  pad |   7 |
| d4 |      |     |
| f6 |      |   2 |
| g7 |      |   5 |

%% daf rows=6; cols=3; keyfield='id'; name=''

>>> daf.append(lol=[['h8', 'cap', 1], ['i9', 'ink', 4]])

| id | item | qty |
| -: | ---: | --: |
| a1 |  pen |   3 |
| b2 |      |     |
| c3 |  pad |   7 |
| d4 |      |     |
| f6 |      |   2 |
| g7 |      |   5 |
| h8 |  cap |   1 |
| i9 |  ink |   4 |

%% daf rows=8; cols=3; keyfield='id'; name=''

>>> more = Daf(cols=['id', 'item', 'qty'], lol=[['j10', 'pen', 6]])
>>> daf.append(more)

| id  | item | qty |
| --: | ---: | --: |
|  a1 |  pen |   3 |
|  b2 |      |     |
|  c3 |  pad |   7 |
|  d4 |      |     |
|  f6 |      |   2 |
|  g7 |      |   5 |
|  h8 |  cap |   1 |
|  i9 |  ink |   4 |
| j10 |  pen |   6 |

%% daf rows=9; cols=3; keyfield='id'; name=''

One row whose values are lists, with la=:

>>> tags = Daf(cols=['id', 'tags'], keyfield='id')
>>> tags.append(la=['a1', ['red', 'large']])

| id |       tags       |
| -: | ---------------: |
| a1 | ['red', 'large'] |

%% daf rows=1; cols=2; keyfield='id'; name=''

A repeated key is added again, unless respect_kd=True, which replaces the row:

>>> stock = Daf(cols=['id', 'qty'], lol=[['a1', 3], ['b2', 10]], keyfield='id')
>>> stock.append({'id': 'a1', 'qty': 30}, respect_kd=True)

| id | qty |
| -: | --: |
| a1 |  30 |
| b2 |  10 |

%% daf rows=2; cols=2; keyfield='id'; name=''

Nothing to add, as None or an empty dict, list or Daf, changes nothing:

>>> stock.append(None).append({}).append([]).append(Daf())

| id | qty |
| -: | --: |
| a1 |  30 |
| b2 |  10 |

%% daf rows=2; cols=2; keyfield='id'; name=''

fast=True, with a KeyedList from default_record(). A row of the wrong length raises:

>>> from daffodil.keyedlist import KeyedList
>>> row = stock.default_record(astype=KeyedList)
>>> row['id'], row['qty'] = 'c3', 7
>>> stock.append(row, fast=True)

| id | qty |
| -: | --: |
| a1 |  30 |
| b2 |  10 |
| c3 |   7 |

%% daf rows=3; cols=2; keyfield='id'; name=''

>>> stock.append(['d4'], fast=True)
Traceback (most recent call last):
...
ValueError: append(fast=True): row 3 has 1 values for 2 columns. With fast=True a list must have one value for each column, in column order. Leave out fast to pad a short list with NULL.

concat

concat(other_instance, respect_kd=False)

Add the rows of another Daf to the end of this one.

Use this to combine two tables with the same columns. By default every row is appended, so a key that exists in both tables appears twice afterwards. Pass respect_kd=True to get an upsert instead.

Parameters:

Name Type Description Default
other_instance 'Daf'

Daf whose rows are added. It is not changed. A SqlDaf is read into memory first.

required
respect_kd bool

If False, the default, append every row without looking at the keys. If True, replace the row that has the same key and append the rows with new keys.

False

Returns:

Type Description
'Daf'

This Daf, which has been changed in place. The rows are deep copies.

Raises:

Type Description
KeyError

The columns differ, in name or in order. The message names the columns found in only one.

ValueError

With respect_kd=True, both Daf instances have a keyfield and the keyfields differ.

Notes

The columns must be equal, including their order. With respect_kd=True, this Daf's keyfield decides the key. If it has no keyfield, the rows are simply appended. A key repeated in the other Daf replaces the earlier row, so the last one wins. If the other Daf is empty, nothing happens. A SqlDaf is read with to_daf(), so all its rows come into memory. Select the rows first.

Examples:

Create two small Daf tables of people, with one key in both:

>>> a_daf = Daf(cols=['id', 'name'], lol=[[1, 'Ana Lopez'], [2, 'Ben Okafor']], keyfield='id')
>>> a_daf

| id |    name    |
| -: | ---------: |
|  1 |  Ana Lopez |
|  2 | Ben Okafor |

%% daf rows=2; cols=2; keyfield='id'; name=''

>>> b_daf = Daf(cols=['id', 'name'], lol=[[2, 'Ben O. Okafor'], [3, 'Chen Wu']])
>>> b_daf

| id |     name      |
| -: | ------------: |
|  2 | Ben O. Okafor |
|  3 |       Chen Wu |

%% daf rows=2; cols=2; keyfield=''; name=''

Add the rows of the second to the first. A Daf does not check keys, so key 2 is there twice:

>>> a_daf.concat(b_daf)

| id |     name      |
| -: | ------------: |
|  1 |     Ana Lopez |
|  2 |    Ben Okafor |
|  2 | Ben O. Okafor |
|  3 |       Chen Wu |

%% daf rows=4; cols=2; keyfield='id'; name=''

>>> a_daf = Daf(cols=['id', 'name'], lol=[[1, 'Ana Lopez'], [2, 'Ben Okafor']], keyfield='id')
>>> a_daf

| id |    name    |
| -: | ---------: |
|  1 |  Ana Lopez |
|  2 | Ben Okafor |

%% daf rows=2; cols=2; keyfield='id'; name=''

Start again, and add them with respect_kd=True. A row whose key is there replaces that row:

>>> a_daf.concat(b_daf, respect_kd=True)

| id |     name      |
| -: | ------------: |
|  1 |     Ana Lopez |
|  2 | Ben O. Okafor |
|  3 |       Chen Wu |

%% daf rows=3; cols=2; keyfield='id'; name=''

extend

extend(records_lod=None, respect_kd=False, *, lol=None)

Append several records, given as a list of dicts or as a list of lists.

Give a list of dicts as records_lod. Each dict is a row, placed by column name, as in append(). A Daf with no columns takes them from the first dict. An empty list, or a list that holds one empty dict, adds nothing.

Give a list of lists as lol, as in extend(lol=[[2, 'b'], [3, 'c']]). Each list is a row, in column order. A short list is padded with NULL. A list with more values than there are columns raises ValueError, and then no row is added. A Daf with no columns takes the lists as they are. The keyword says that these are several rows, and not one row whose cells are lists. For that, see append(la=...).

Without respect_kd, a key that already exists is added again. Use respect_kd=True when the keyfield must stay unique.

Parameters:

Name Type Description Default
records_lod T_loda | None

The records, as dicts.

None
respect_kd bool

If True, replace the row that has the same key. If False, the default, add it.

False
lol T_lola | None

The rows, as lists of values in column order.

None

Returns:

Type Description
'Daf'

This Daf, which has been changed.

Raises:

Type Description
TypeError

Both records_lod and lol are given, or a row of lol is not a list.

ValueError

A row of lol has more values than there are columns.

Examples:

Create a small Daf of people, keyed by id:

>>> daf = Daf(cols=['id', 'name'], lol=[[1, 'Ana Lopez']], keyfield='id')
>>> daf

| id |   name    |
| -: | --------: |
|  1 | Ana Lopez |

%% daf rows=1; cols=2; keyfield='id'; name=''

Add rows as dicts. With respect_kd=True, key 1 replaces its row:

>>> daf.extend([{'id': 2, 'name': 'Ben Okafor'}, {'id': 1, 'name': 'Ana L. Lopez'}], respect_kd=True)

| id |     name     |
| -: | -----------: |
|  1 | Ana L. Lopez |
|  2 |   Ben Okafor |

%% daf rows=2; cols=2; keyfield='id'; name=''

Add rows as lists. A short list is padded:

>>> daf.extend(lol=[[3, 'Chen Wu'], [4]])

| id |     name     |
| -: | -----------: |
|  1 | Ana L. Lopez |
|  2 |   Ben Okafor |
|  3 |      Chen Wu |
|  4 |              |

%% daf rows=4; cols=2; keyfield='id'; name=''

record_append

record_append(record, respect_kd=True)

Add one row that is given as a dict or a KeyedList.

This is the single row case of append(). The row is placed by column name, a missing key gets NULL, and a key that is not a column is dropped. An empty Daf takes its columns from the first row. An empty record adds nothing.

With a keyfield, the row that has the same key is replaced, and a new key is added at the end. This is the default here, unlike append(). Pass respect_kd=False to always add. The key index is kept up to date, so adding many rows one at a time stays fast.

A plain list is not accepted. Use append() for that.

Parameters:

Name Type Description Default
record T_da | KeyedList

The row, as a dict or a KeyedList.

required
respect_kd bool

If True, the default, replace the row that has the same key. Otherwise add it.

True

Returns:

Type Description
'Daf'

This Daf, which has been changed.

Examples:

Create a small Daf of people, keyed by id:

>>> daf = Daf(cols=['id', 'name'], lol=[[1, 'Ana Lopez'], [2, 'Ben Okafor']], keyfield='id')
>>> daf

| id |    name    |
| -: | ---------: |
|  1 |  Ana Lopez |
|  2 | Ben Okafor |

%% daf rows=2; cols=2; keyfield='id'; name=''

Add a row whose key is there. By default it replaces that row:

>>> daf.record_append({'id': 2, 'name': 'Ben O. Okafor'})

| id |     name      |
| -: | ------------: |
|  1 |     Ana Lopez |
|  2 | Ben O. Okafor |

%% daf rows=2; cols=2; keyfield='id'; name=''

With respect_kd=False, it is added as another row:

>>> daf.record_append({'id': 2, 'name': 'Ben Okafor Jr.'}, respect_kd=False)

| id |      name      |
| -: | -------------: |
|  1 |      Ana Lopez |
|  2 |  Ben O. Okafor |
|  2 | Ben Okafor Jr. |

%% daf rows=3; cols=2; keyfield='id'; name=''

Records

assign_record

assign_record(record)

Put one row in the Daf by its key, replacing a row that has the same key.

The row is a dict. If a row with that key exists, the whole row is replaced. The cells of columns that the dict lacks become NULL. If the key is new, the row is added at the end. This is an upsert for one row. For that, append() with respect_kd=True also works. Use update_by_keylist() to change only some cells.

Parameters:

Name Type Description Default
record T_da

The row, as a dict. It must have the keyfield.

required

Returns:

Type Description
'Daf'

This Daf, which has been changed.

Raises:

Type Description
KeysDisabledError

The Daf has no keyfield.

Examples:

Create a small Daf of people, keyed by an int id:

>>> daf = Daf(cols=['id', 'city', 'age'], lol=[[1, 'Denver', 34], [2, 'Austin', 52], [3, 'Boston', 27]], keyfield='id')
>>> daf

| id |  city  | age |
| -: | -----: | --: |
|  1 | Denver |  34 |
|  2 | Austin |  52 |
|  3 | Boston |  27 |

%% daf rows=3; cols=3; keyfield='id'; name=''

Replace the row with key 2. Columns the dict lacks become NULL:

>>> daf.assign_record({'id': 2, 'city': 'Miami'})

| id |  city  | age |
| -: | -----: | --: |
|  1 | Denver |  34 |
|  2 |  Miami |     |
|  3 | Boston |  27 |

%% daf rows=3; cols=3; keyfield='id'; name=''

assign_record_irow

assign_record_irow(irow=None, record=None)

Put one row in the Daf by position, replacing the row there.

The row is a dict. The whole row is replaced, and the cells of columns that the dict lacks become NULL. Use update_record_irow() to change only some cells.

With the default position, None, the row is added at the end. So it is with a position beyond the last row, and with any position when the Daf has no rows. A negative position counts from the end, as in a list, so -1 replaces the last row. This is also what my_daf[-1] = {...} does.

This does not update the key index (kd), so don't change a key with it. See __setitem__.

Parameters:

Name Type Description Default
irow int | None

The row position. None, the default, adds the row at the end.

None
record T_da | None

The row, as a dict. If None, nothing happens.

None

Returns:

Type Description
'Daf'

This Daf, which has been changed.

Raises:

Type Description
IndexError

A negative position is before the first row, for a Daf that has rows.

Examples:

Create a small Daf of people:

>>> daf = Daf(cols=['id', 'city', 'age'], lol=[[1, 'Denver', 34], [2, 'Austin', 52], [3, 'Boston', 27]], keyfield='id')
>>> daf

| id |  city  | age |
| -: | -----: | --: |
|  1 | Denver |  34 |
|  2 | Austin |  52 |
|  3 | Boston |  27 |

%% daf rows=3; cols=3; keyfield='id'; name=''

Replace the row at position 1. Columns the dict lacks become NULL:

>>> daf.assign_record_irow(1, {'city': 'Miami'})

| id |  city  | age |
| -: | -----: | --: |
|  1 | Denver |  34 |
|    |  Miami |     |
|  3 | Boston |  27 |

%% daf rows=3; cols=3; keyfield='id'; name=''

Replace the last row:

>>> daf.assign_record_irow(-1, {'id': 9})

| id |  city  | age |
| -: | -----: | --: |
|  1 | Denver |  34 |
|    |  Miami |     |
|  9 |        |     |

%% daf rows=3; cols=3; keyfield='id'; name=''

With no position, add a row at the end:

>>> daf.assign_record_irow(record={'id': 10})

| id |  city  | age |
| -: | -----: | --: |
|  1 | Denver |  34 |
|    |  Miami |     |
|  9 |        |     |
| 10 |        |     |

%% daf rows=4; cols=3; keyfield='id'; name=''

update_by_keylist

update_by_keylist(keylist=None, record=None)

Change some cells in the rows that have the given keys.

Only the columns that are keys of the dict are changed. Other cells keep their values. A key that is not found is skipped. This is a bulk form of update_record_krow(), for rows that all take the same values. The row positions do not change, so the key index stays valid.

Parameters:

Name Type Description Default
keylist T_ls | None

The keys of the rows to change.

None
record T_da | None

The new values, as a dict of column name and value. Names that are not columns are ignored.

None

Returns:

Type Description
'Daf'

This Daf, which has been changed. With no keyfield, rows, keys or record, nothing happens.

Examples:

Create a small Daf of people, keyed by an int id:

>>> daf = Daf(cols=['id', 'city', 'age'], lol=[[1, 'Denver', 34], [2, 'Austin', 52], [3, 'Boston', 27]], keyfield='id')
>>> daf

| id |  city  | age |
| -: | -----: | --: |
|  1 | Denver |  34 |
|  2 | Austin |  52 |
|  3 | Boston |  27 |

%% daf rows=3; cols=3; keyfield='id'; name=''

Change the city of the people with keys 1 and 3. Key 9 is not found and is skipped:

>>> daf.update_by_keylist([1, 3, 9], {'city': 'Miami'})

| id |  city  | age |
| -: | -----: | --: |
|  1 |  Miami |  34 |
|  2 | Austin |  52 |
|  3 |  Miami |  27 |

%% daf rows=3; cols=3; keyfield='id'; name=''

update_record_irow

update_record_irow(irow=-1, record=None)

Change some cells in the row at a position.

Only the columns that are keys of the dict are changed. Other cells keep their values. A negative position counts from the end, as in a list, so the default, -1, is the last row. A position that is out of range raises IndexError, and nothing is changed. A Daf with no rows or no columns, and a record of None, change nothing.

This does not update the key index (kd), so don't change a key with it. See __setitem__.

Parameters:

Name Type Description Default
irow int

The row position. -1, the default, is the last row.

-1
record T_da | None

The new values, as a dict of column name and value. Names that are not columns are ignored.

None

Returns:

Type Description
'Daf'

This Daf, which has been changed.

Raises:

Type Description
IndexError

The position is out of range, for a Daf that has rows and columns.

Examples:

Create a small Daf of people:

>>> daf = Daf(cols=['id', 'city', 'age'], lol=[[1, 'Denver', 34], [2, 'Austin', 52], [3, 'Boston', 27]], keyfield='id')
>>> daf

| id |  city  | age |
| -: | -----: | --: |
|  1 | Denver |  34 |
|  2 | Austin |  52 |
|  3 | Boston |  27 |

%% daf rows=3; cols=3; keyfield='id'; name=''

Change some cells of the row at position 1:

>>> daf.update_record_irow(1, {'city': 'Miami'})

| id |  city  | age |
| -: | -----: | --: |
|  1 | Denver |  34 |
|  2 |  Miami |  52 |
|  3 | Boston |  27 |

%% daf rows=3; cols=3; keyfield='id'; name=''

With no position, change the last row:

>>> daf.update_record_irow(record={'age': 61})

| id |  city  | age |
| -: | -----: | --: |
|  1 | Denver |  34 |
|  2 |  Miami |  52 |
|  3 | Boston |  61 |

%% daf rows=3; cols=3; keyfield='id'; name=''

update_record_krow

update_record_krow(key, record=None)

Change some cells in the row that has this key.

Only the columns that are keys of the dict are changed. Other cells keep their values. It is the form of update_record_irow() that finds the row by its key. An int is always a key here, never a position, so it suits a keyfield of ints. For many rows that take the same values, use update_by_keylist().

As with update_record_irow(), this does not update the key index (kd), so don't change a key with it. See __setitem__. A record of None changes nothing.

Parameters:

Name Type Description Default
key Any

The key of the row to change.

required
record T_da | None

The new values, as a dict of column name and value. Names that are not columns are ignored.

None

Returns:

Type Description
'Daf'

This Daf, which has been changed.

Raises:

Type Description
KeyError

No row has this key.

ValueError

The Daf has no keyfield.

Examples:

Create a small Daf of people, keyed by an int id:

>>> daf = Daf(cols=['id', 'city', 'age'], lol=[[1, 'Denver', 34], [2, 'Austin', 52], [3, 'Boston', 27]], keyfield='id')
>>> daf

| id |  city  | age |
| -: | -----: | --: |
|  1 | Denver |  34 |
|  2 | Austin |  52 |
|  3 | Boston |  27 |

%% daf rows=3; cols=3; keyfield='id'; name=''

Change some cells of the row with key 2. An int here is a key:

>>> daf.update_record_krow(2, {'city': 'Miami'})

| id |  city  | age |
| -: | -----: | --: |
|  1 | Denver |  34 |
|  2 |  Miami |  52 |
|  3 | Boston |  27 |

%% daf rows=3; cols=3; keyfield='id'; name=''

insert_irow

insert_irow(irow=None, row=None, default='')

Insert a row at a position and move the later rows down.

The row is a list of values, or a dict that is placed by column name. A short list is filled out with default. With the default position, None, or with a position beyond the last row, the row is added at the end. A negative position, such as -1, also adds it at the end. This differs from list.insert(), which puts the item before the last one. Prefer None. The key index is rebuilt when it is next needed.

Parameters:

Name Type Description Default
irow int | None

The row position. None, the default, adds the row at the end.

None
row T_la | T_da | None

The row, as a list or a dict.

None
default Any

The value for cells that a short list does not reach.

''

Returns:

Type Description
'Daf'

This Daf, which has been changed.

Raises:

Type Description
TypeError

The row is not a list or a dict. This includes the default, None.

Examples:

Create a small Daf of people:

>>> daf = Daf(cols=['id', 'city', 'age'], lol=[[1, 'Denver', 34], [2, 'Austin', 52], [3, 'Boston', 27]], keyfield='id')
>>> daf

| id |  city  | age |
| -: | -----: | --: |
|  1 | Denver |  34 |
|  2 | Austin |  52 |
|  3 | Boston |  27 |

%% daf rows=3; cols=3; keyfield='id'; name=''

Insert a row at position 1, from a dict:

>>> daf.insert_irow(1, {'id': 9, 'city': 'Reno'})

| id |  city  | age |
| -: | -----: | --: |
|  1 | Denver |  34 |
|  9 |   Reno |     |
|  2 | Austin |  52 |
|  3 | Boston |  27 |

%% daf rows=4; cols=3; keyfield='id'; name=''

A short list is filled out with default:

>>> stock = Daf(cols=['id', 'item', 'qty'], lol=[['a1', 'pen', 3], ['b2', 'ink', 10]], keyfield='id')
>>> stock.insert_irow(1, ['z0'], default='?')

| id | item | qty |
| -: | ---: | --: |
| a1 |  pen |   3 |
| z0 |    ? |   ? |
| b2 |  ink |  10 |

%% daf rows=3; cols=3; keyfield='id'; name=''

Columns

assign_col

assign_col(colname, la=None, default='')

Fill a column by name with the values of a list, or add it if it is new.

This is my_daf[:, colname] = values, and it also adds a column. A list that is too short is filled out with default. With no list, every cell gets default. If the column is the keyfield, the key index is rebuilt when it is next needed.

Parameters:

Name Type Description Default
colname str

The column name.

required
la T_la | None

The values, one for each row.

None
default Any

The value for rows that the list does not reach.

''

Returns:

Type Description
'Daf'

This Daf, which has been changed.

Examples:

Create a small Daf of people:

>>> daf = Daf(cols=['id', 'city', 'age'], lol=[[1, 'Denver', 34], [2, 'Austin', 52], [3, 'Boston', 27]], keyfield='id')
>>> daf

| id |  city  | age |
| -: | -----: | --: |
|  1 | Denver |  34 |
|  2 | Austin |  52 |
|  3 | Boston |  27 |

%% daf rows=3; cols=3; keyfield='id'; name=''

Add a column with a default in every row:

>>> daf.assign_col('visits', default=0)

| id |  city  | age | visits |
| -: | -----: | --: | -----: |
|  1 | Denver |  34 |      0 |
|  2 | Austin |  52 |      0 |
|  3 | Boston |  27 |      0 |

%% daf rows=3; cols=4; keyfield='id'; name=''

A list shorter than the rows is filled out with default. A new name adds a column at the right:

>>> stock = Daf(cols=['id', 'qty'], lol=[['a1', 3], ['b2', 10], ['c3', 7]], keyfield='id')
>>> stock.assign_col('qty', [1], default=0)

| id | qty |
| -: | --: |
| a1 |   1 |
| b2 |   0 |
| c3 |   0 |

%% daf rows=3; cols=2; keyfield='id'; name=''

>>> stock.assign_col('note', ['n1', 'n2', 'n3'])

| id | qty | note |
| -: | --: | ---: |
| a1 |   1 |   n1 |
| b2 |   0 |   n2 |
| c3 |   0 |   n3 |

%% daf rows=3; cols=3; keyfield='id'; name=''

assign_icol

assign_icol(icol=-1, col_la=None, default='')

Fill a column by position with the values of a list.

A list that is too short is filled out with default. With no list, every cell gets default. With icol=-1 a new column is added at the right. If the Daf has column names, the new column gets the next spreadsheet name, such as C, made unique. Use insert_col() to add a column with a name of your own.

Parameters:

Name Type Description Default
icol int

The column position. -1 adds a column at the right.

-1
col_la T_la | None

The values, one for each row.

None
default Any

The value for rows that the list does not reach.

''

Returns:

Type Description
'Daf'

This Daf, which has been changed.

Examples:

Create a small Daf of people:

>>> daf = Daf(cols=['id', 'city', 'age'], lol=[[1, 'Denver', 34], [2, 'Austin', 52], [3, 'Boston', 27]], keyfield='id')
>>> daf

| id |  city  | age |
| -: | -----: | --: |
|  1 | Denver |  34 |
|  2 | Austin |  52 |
|  3 | Boston |  27 |

%% daf rows=3; cols=3; keyfield='id'; name=''

Fill the column at position 1 from a list. A short list is filled out with default:

>>> daf.assign_icol(1, ['Miami', 'Reno'], default='unknown')

| id |  city   | age |
| -: | ------: | --: |
|  1 |   Miami |  34 |
|  2 |    Reno |  52 |
|  3 | unknown |  27 |

%% daf rows=3; cols=3; keyfield='id'; name=''

insert_col

insert_col(colname, col_la=None, icol=-1, default='')

Add a named column at a position, or overwrite it if the name exists.

A list that is too short is filled out with default. With no list, every cell gets default, so this can add a constant column. If the name already exists the column is overwritten, and icol is ignored. An empty name does nothing. Use set_keyfield() if the column is to be the keyfield.

When a column is added and the rows are shared with another Daf, as after a selection, this Daf first takes its own copies of the rows. The other Daf is not changed.

Parameters:

Name Type Description Default
colname str

The name of the column.

required
col_la T_la | None

The values, one for each row.

None
icol int

The column position. -1 adds the column at the right.

-1
default Any

The value for rows that the list does not reach.

''

Returns:

Type Description
'Daf'

This Daf, which has been changed.

Examples:

Create a small Daf of people:

>>> daf = Daf(cols=['id', 'city', 'age'], lol=[[1, 'Denver', 34], [2, 'Austin', 52], [3, 'Boston', 27]], keyfield='id')
>>> daf

| id |  city  | age |
| -: | -----: | --: |
|  1 | Denver |  34 |
|  2 | Austin |  52 |
|  3 | Boston |  27 |

%% daf rows=3; cols=3; keyfield='id'; name=''

Insert a column at position 1, from a list, and another at the end with a default:

>>> daf.insert_col('visits', [5, 3, 8], icol=1)

| id | visits |  city  | age |
| -: | -----: | -----: | --: |
|  1 |      5 | Denver |  34 |
|  2 |      3 | Austin |  52 |
|  3 |      8 | Boston |  27 |

%% daf rows=3; cols=4; keyfield='id'; name=''

>>> daf.insert_col('score', default=100)

| id | visits |  city  | age | score |
| -: | -----: | -----: | --: | ----: |
|  1 |      5 | Denver |  34 |   100 |
|  2 |      3 | Austin |  52 |   100 |
|  3 |      8 | Boston |  27 |   100 |

%% daf rows=3; cols=5; keyfield='id'; name=''

insert_icol

insert_icol(icol=-1, col_la=None, colname='', default='')

Insert a column at a position and move the later columns right.

A list that is too short is filled out with default. With icol=-1, or a position beyond the last column, the column is added at the right. Give colname to name it. Without a name, if the Daf has column names, the column gets the next spreadsheet name, such as C, made unique. The dtypes are not changed. Use set_keyfield() if the column is to be the keyfield.

If the rows are shared with another Daf, as after a selection, this Daf first takes its own copies of the rows. The other Daf is not changed.

Parameters:

Name Type Description Default
icol int

The column position. -1 adds the column at the right.

-1
col_la T_la | None

The values, one for each row.

None
colname str

The name of the new column.

''
default Any

The value for rows that the list does not reach.

''

Returns:

Type Description
'Daf'

This Daf, which has been changed.

Examples:

Create a small Daf of people:

>>> daf = Daf(cols=['id', 'city', 'age'], lol=[[1, 'Denver', 34], [2, 'Austin', 52], [3, 'Boston', 27]], keyfield='id')
>>> daf

| id |  city  | age |
| -: | -----: | --: |
|  1 | Denver |  34 |
|  2 | Austin |  52 |
|  3 | Boston |  27 |

%% daf rows=3; cols=3; keyfield='id'; name=''

Insert a new column at position 1:

>>> daf.insert_icol(1, [5, 3, 8], colname='visits')

| id | visits |  city  | age |
| -: | -----: | -----: | --: |
|  1 |      5 | Denver |  34 |
|  2 |      3 | Austin |  52 |
|  3 |      8 | Boston |  27 |

%% daf rows=3; cols=4; keyfield='id'; name=''

A list shorter than the rows is filled out with default:

>>> stock = Daf(cols=['id', 'qty'], lol=[['a1', 3], ['b2', 10], ['c3', 7]], keyfield='id')
>>> stock.insert_icol(1, ['red'], 'color', default='none')

| id | color | qty |
| -: | ----: | --: |
| a1 |   red |   3 |
| b2 |  none |  10 |
| c3 |  none |   7 |

%% daf rows=3; cols=3; keyfield='id'; name=''

insert_idx_col

insert_idx_col(colname='idx', icol=0, startat=0)

Insert a column of row numbers.

This is insert_col(), so rows shared with another Daf are copied first and the other Daf is not changed.

Parameters:

Name Type Description Default
colname str

The name of the new column.

'idx'
icol int

The column position.

0
startat int

The number of the first row.

0

Returns:

Type Description
'Daf'

This Daf, which has been changed.

Examples:

Create a small Daf of people:

>>> daf = Daf(cols=['id', 'city', 'age'], lol=[[1, 'Denver', 34], [2, 'Austin', 52], [3, 'Boston', 27]], keyfield='id')
>>> daf

| id |  city  | age |
| -: | -----: | --: |
|  1 | Denver |  34 |
|  2 | Austin |  52 |
|  3 | Boston |  27 |

%% daf rows=3; cols=3; keyfield='id'; name=''

Insert a column of row numbers, from 0:

>>> daf.insert_idx_col()

| idx | id |  city  | age |
| --: | -: | -----: | --: |
|   0 |  1 | Denver |  34 |
|   1 |  2 | Austin |  52 |
|   2 |  3 | Boston |  27 |

%% daf rows=3; cols=4; keyfield='id'; name=''

Another name, in another place, numbered from 1:

>>> stock = Daf(cols=['id', 'qty'], lol=[['a1', 3], ['b2', 10], ['c3', 7]], keyfield='id')
>>> stock.insert_idx_col('row_no', icol=1, startat=1)

| id | row_no | qty |
| -: | -----: | --: |
| a1 |      1 |   3 |
| b2 |      2 |  10 |
| c3 |      3 |   7 |

%% daf rows=3; cols=3; keyfield='id'; name=''

set_col_irows

set_col_irows(colname, irows, val)

Set one value in the given rows of a named column.

This is deprecated. Use my_daf[irows, colname] = value, which does the same. A column name that is not found raises KeyError. Row positions that are out of range are skipped.

Parameters:

Name Type Description Default
colname str

The column name.

required
irows T_li

The row positions.

required
val Any

The value to set.

required

Returns:

Type Description
'Daf'

This Daf, which has been changed.

Raises:

Type Description
KeyError

The column name is not found.

Examples:

Create a small Daf of people:

>>> daf = Daf(cols=['id', 'city', 'age'], lol=[[1, 'Denver', 34], [2, 'Austin', 52], [3, 'Boston', 27]], keyfield='id')
>>> daf

| id |  city  | age |
| -: | -----: | --: |
|  1 | Denver |  34 |
|  2 | Austin |  52 |
|  3 | Boston |  27 |

%% daf rows=3; cols=3; keyfield='id'; name=''

Set the city of the rows at positions 0 and 2:

>>> daf.set_col_irows('city', [0, 2], 'unknown')

| id |  city   | age |
| -: | ------: | --: |
|  1 | unknown |  34 |
|  2 |  Austin |  52 |
|  3 | unknown |  27 |

%% daf rows=3; cols=3; keyfield='id'; name=''

set_icol

set_icol(icol, val)

Set one value in every row of a column, by position.

This is daf[:, icol] = value. A negative position counts from the end. To give each row a value of its own, assign a list, as daf[:, icol] = values.

Parameters:

Name Type Description Default
icol int

The column position.

required
val Any

The value to set.

required

Returns:

Type Description
'Daf'

This Daf, which has been changed.

Raises:

Type Description
IndexError

The position is beyond the end of a row.

Examples:

Create a small Daf of people:

>>> daf = Daf(cols=['id', 'city', 'age'], lol=[[1, 'Denver', 34], [2, 'Austin', 52], [3, 'Boston', 27]], keyfield='id')
>>> daf

| id |  city  | age |
| -: | -----: | --: |
|  1 | Denver |  34 |
|  2 | Austin |  52 |
|  3 | Boston |  27 |

%% daf rows=3; cols=3; keyfield='id'; name=''

Set every value of the column at position 1:

>>> daf.set_icol(1, 'unknown')

| id |  city   | age |
| -: | ------: | --: |
|  1 | unknown |  34 |
|  2 | unknown |  52 |
|  3 | unknown |  27 |

%% daf rows=3; cols=3; keyfield='id'; name=''

set_icol_irows

set_icol_irows(icol, irows, val)

Set one value in the given rows of a column, by position.

It is like daf[irows, icol] = value, with one difference. A row position past the end, or a negative one, is skipped. A negative position is not counted from the end, as in brackets.

Parameters:

Name Type Description Default
icol int

The column position.

required
irows T_li

The row positions.

required
val Any

The value to set.

required

Returns:

Type Description
'Daf'

This Daf, which has been changed.

Examples:

Create a small Daf of people:

>>> daf = Daf(cols=['id', 'city', 'age'], lol=[[1, 'Denver', 34], [2, 'Austin', 52], [3, 'Boston', 27]], keyfield='id')
>>> daf

| id |  city  | age |
| -: | -----: | --: |
|  1 | Denver |  34 |
|  2 | Austin |  52 |
|  3 | Boston |  27 |

%% daf rows=3; cols=3; keyfield='id'; name=''

Set the column at position 1 in some rows. Position 9 is past the end, and -1 is negative, so both are skipped:

>>> daf.set_icol_irows(1, [0, 9, -1], 'unknown')

| id |  city   | age |
| -: | ------: | --: |
|  1 | unknown |  34 |
|  2 |  Austin |  52 |
|  3 |  Boston |  27 |

%% daf rows=3; cols=3; keyfield='id'; name=''

Removing

delete_records

delete_records(keys_ls, inplace=False, silent_error=False)

Remove the rows with these keys.

By default, this Daf is left as it is, and a new Daf without the rows is returned, as select_records(keys, inverse=True) gives. That is the usual way in daffodil, and the new Daf shares the rows that remain.

With inplace=True, the rows are deleted from this Daf itself, and it is returned. The row list is rebuilt once, in place, so it costs one pass however many rows go. The remaining rows keep their order, and the key index is rebuilt when next needed. That is safe for a Daf in memory: a selection made from it earlier holds its own row list, so it still has the deleted rows. On a SqlDaf parent table it is not safe in the same way. See SqlDaf.delete_records() in sqldaf.py.

The keys may be a list, any iterable, or another Daf, whose keys are then used through a view of its key index, as in select_records().

Parameters:

Name Type Description Default
keys_ls 'T_ls | Iterable | Daf'

The keys of the rows to remove, or a Daf whose keys are used.

required
inplace bool

If True, delete from this Daf and return it. If False, return a new Daf.

False
silent_error bool

If True, keys that are not found are ignored.

False

Returns:

Type Description
The Daf without the rows

this one if inplace, otherwise a new one.

Raises:

Type Description
KeysDisabledError

This Daf, or a Daf given as the keys, has no keyfield and no key index.

KeyError

A key is not found and silent_error is False. Nothing is removed.

Examples:

Create a small Daf of people, keyed by id:

>>> daf = Daf(cols=['id', 'name'], lol=[['p1', 'Ana Lopez'], ['p2', 'Ben Okafor'], ['p3', 'Chen Wu']], keyfield='id')
>>> daf

| id |    name    |
| -: | ---------: |
| p1 |  Ana Lopez |
| p2 | Ben Okafor |
| p3 |    Chen Wu |

%% daf rows=3; cols=2; keyfield='id'; name=''

By default, get a Daf without the rows. The table keeps them:

>>> daf.delete_records(['p2'])

| id |   name    |
| -: | --------: |
| p1 | Ana Lopez |
| p3 |   Chen Wu |

%% daf rows=2; cols=2; keyfield='id'; name=''

>>> daf

| id |    name    |
| -: | ---------: |
| p1 |  Ana Lopez |
| p2 | Ben Okafor |
| p3 |    Chen Wu |

%% daf rows=3; cols=2; keyfield='id'; name=''

Delete them from the table itself, ignoring a key that is not found:

>>> daf.delete_records(['p2', 'p9'], inplace=True, silent_error=True)

| id |   name    |
| -: | --------: |
| p1 | Ana Lopez |
| p3 |   Chen Wu |

%% daf rows=2; cols=2; keyfield='id'; name=''

remove_key

remove_key(keyval, silent_error=False)

Make a new Daf without the row that has the given key.

This is deprecated. Use select_krows(key, inverse=True), which does the same.

This does not remove the row from this Daf. It returns a new Daf that leaves the row out, and this Daf is unchanged. Keep the result, as in daf = daf.remove_key(2).

The new Daf shares the surviving rows with this Daf. Changing a cell in one changes it in the other. Call copy('editable') if you need row lists of your own.

A tuple is a range of keys, as in remove_key((2, 3)). With a composite keyfield, a tuple as long as the keyfield, with no tuples inside it, is one key, as in remove_key(('a', 1)). A tuple of key tuples is a range, and a list of key tuples is a list of keys.

Parameters:

Name Type Description Default
keyval str | int | T_la | T_ta | None

The key of the row to leave out.

required
silent_error bool

If True, a key that is not found is ignored.

False

Returns:

Type Description
'Daf'

The new Daf. It has the same keyfield.

Raises:

Type Description
KeysDisabledError

The Daf has no keyfield and no key index.

KeyError

The key is not found and silent_error is False.

Examples:

Create a small Daf of people, keyed by id:

>>> daf = Daf(cols=['id', 'name'], lol=[[1, 'Ana Lopez'], [2, 'Ben Okafor']], keyfield='id')
>>> daf

| id |    name    |
| -: | ---------: |
|  1 |  Ana Lopez |
|  2 | Ben Okafor |

%% daf rows=2; cols=2; keyfield='id'; name=''

Remove the row with key 1:

>>> daf.remove_key(1)

| id |    name    |
| -: | ---------: |
|  2 | Ben Okafor |

%% daf rows=1; cols=2; keyfield='id'; name=''

>>> daf.num_rows()
2

A key of two columns is a tuple:

>>> c_daf = Daf(cols=['city', 'year'], lol=[['Denver', 2023], ['Denver', 2024]], keyfield=('city', 'year'))
>>> c_daf

|  city  | year |
| -----: | ---: |
| Denver | 2023 |
| Denver | 2024 |

%% daf rows=2; cols=2; keyfield='('city', 'year')'; name=''

>>> c_daf.remove_key(('Denver', 2023))

|  city  | year |
| -----: | ---: |
| Denver | 2024 |

%% daf rows=1; cols=2; keyfield='('city', 'year')'; name=''

A key that is not found raises KeyError, or is ignored with silent_error=True:

>>> stock = Daf(cols=['id', 'qty'], lol=[['a1', 3], ['b2', 10]], keyfield='id')
>>> stock.remove_key('z9')
Traceback (most recent call last):
...
KeyError: 'z9'
>>> stock.remove_key('z9', silent_error=True).keys()
['a1', 'b2']

remove_keylist

remove_keylist(keylist, silent_error=False)

Make a new Daf without the rows that have the given keys.

This is deprecated. Use select_krows(keys, inverse=True), which does the same.

This does not remove the rows from this Daf. It returns a new Daf that leaves them out, and this Daf is unchanged. See remove_key() for how the rows are shared.

Parameters:

Name Type Description Default
keylist T_la

The keys of the rows to leave out.

required
silent_error bool

If True, keys that are not found are ignored.

False

Returns:

Type Description
'Daf'

The new Daf. It has the same keyfield.

Raises:

Type Description
KeysDisabledError

The Daf has no keyfield and no key index.

KeyError

A key is not found and silent_error is False.

Examples:

Create a small Daf of people, keyed by id:

>>> daf = Daf(cols=['id', 'name'], lol=[[1, 'Ana Lopez'], [2, 'Ben Okafor'], [3, 'Chen Wu']], keyfield='id')
>>> daf

| id |    name    |
| -: | ---------: |
|  1 |  Ana Lopez |
|  2 | Ben Okafor |
|  3 |    Chen Wu |

%% daf rows=3; cols=2; keyfield='id'; name=''

Remove the rows with keys 1 and 3:

>>> daf.remove_keylist([1, 3])

| id |    name    |
| -: | ---------: |
|  2 | Ben Okafor |

%% daf rows=1; cols=2; keyfield='id'; name=''

A key of two columns is a tuple:

>>> visits_daf = Daf(cols=['year', 'city', 'visits'], lol=[[2023, 'Denver', 14], [2024, 'Austin', 9]], keyfield=['year', 'city'])
>>> visits_daf

| year |  city  | visits |
| ---: | -----: | -----: |
| 2023 | Denver |     14 |
| 2024 | Austin |      9 |

%% daf rows=2; cols=3; keyfield='['year', 'city']'; name=''

>>> visits_daf.remove_keylist([(2023, 'Denver')])

| year |  city  | visits |
| ---: | -----: | -----: |
| 2024 | Austin |      9 |

%% daf rows=1; cols=3; keyfield='['year', 'city']'; name=''

Keys that are not found raise KeyError, or are ignored with silent_error=True:

>>> stock = Daf(cols=['id', 'qty'], lol=[['a1', 3], ['b2', 10], ['c3', 7]], keyfield='id')
>>> stock.remove_keylist(['a1', 'z9'], silent_error=True).keys()
['b2', 'c3']

remove_dups

remove_dups(keyfield='')

Split the rows into those with a unique key and those with a repeated key.

Only the key columns are compared, not the whole row. For each key, the last row is kept as the unique one. The earlier rows with that key are the duplicates. The unique rows are in the order in which their keys first appear.

Without keyfield, the keyfield of this Daf is used. If there is none, a KeysDisabledError is raised. This Daf is not changed. Both results share their rows with it, and both have the key columns as their keyfield.

Parameters:

Name Type Description Default
keyfield str | T_ta | T_la

The column, or tuple or list of columns, that identifies a row. If empty, the keyfield of this Daf.

''

Returns:

Type Description
Tuple['Daf', 'Daf']

A tuple of the Daf of unique rows and the Daf of duplicate rows.

Raises:

Type Description
KeysDisabledError

There is no keyfield and this Daf has none.

KeyError

A key column is not found.

Examples:

Create a small Daf of sign-ups, where one email appears twice:

>>> daf = Daf(cols=['email', 'name'], lol=[['ana@example.com', 'Ana Lopez'], ['ben@example.com', 'Ben Okafor'], ['ana@example.com', 'Ana L.']])
>>> daf

|      email      |    name    |
| --------------: | ---------: |
| ana@example.com |  Ana Lopez |
| ben@example.com | Ben Okafor |
| ana@example.com |     Ana L. |

%% daf rows=3; cols=2; keyfield=''; name=''

Split it into the first row for each email, and the repeats:

>>> unique, dups = daf.remove_dups('email')
>>> unique

|      email      |    name    |
| --------------: | ---------: |
| ana@example.com |     Ana L. |
| ben@example.com | Ben Okafor |

%% daf rows=2; cols=2; keyfield='email'; name=''

>>> dups

|      email      |   name    |
| --------------: | --------: |
| ana@example.com | Ana Lopez |

%% daf rows=1; cols=2; keyfield='email'; name=''

drop_cols

drop_cols(exclude_cols=None)

Remove columns from this Daf, in place.

The rows are rebuilt without those columns, so this copies all the data. Avoid it for large tables. Instead, name only the columns you need: with cols= in reduce(), by reading only those fields in an apply() function, or with select_kcols() for a new Daf.

The column names and dtypes are updated. A name that is not a column is ignored. If a column of the keyfield is dropped, the keyfield is cleared, as in the other methods that remove a key column. Set it again with set_keyfield(). With no names, nothing happens.

Parameters:

Name Type Description Default
exclude_cols T_ls | None

The names of the columns to remove.

None

Returns:

Type Description
'Daf'

This Daf, which has been changed.

Examples:

Create a small Daf of people:

>>> daf = Daf(cols=['id', 'city', 'age'], lol=[[1, 'Denver', 34], [2, 'Austin', 52], [3, 'Boston', 27]], keyfield='id')
>>> daf

| id |  city  | age |
| -: | -----: | --: |
|  1 | Denver |  34 |
|  2 | Austin |  52 |
|  3 | Boston |  27 |

%% daf rows=3; cols=3; keyfield='id'; name=''

Drop a column:

>>> daf.drop_cols(['city'])

| id | age |
| -: | --: |
|  1 |  34 |
|  2 |  52 |
|  3 |  27 |

%% daf rows=3; cols=2; keyfield='id'; name=''

Find and replace

find_replace

find_replace(find_pat, replace_val)

Replace every cell that matches a pattern, in place.

Each cell is converted to text and searched with the regular expression find_pat. If it matches anywhere in the text, the whole cell is replaced by replace_val. It is not a substitution inside the text. Every column is searched, including numbers, and the key index is rebuilt when it is next needed.

Parameters:

Name Type Description Default
find_pat str

A regular expression.

required
replace_val Any

The value that replaces a matching cell.

required

Returns:

Type Description
'Daf'

This Daf, which has been changed.

Examples:

Create a small Daf of people:

>>> daf = Daf(cols=['id', 'city', 'age'], lol=[[1, 'Denver', 34], [2, 'Austin', 52], [3, 'Boston', 27]], keyfield='id')
>>> daf

| id |  city  | age |
| -: | -----: | --: |
|  1 | Denver |  34 |
|  2 | Austin |  52 |
|  3 | Boston |  27 |

%% daf rows=3; cols=3; keyfield='id'; name=''

Replace every cell that matches a regular expression:

>>> daf.find_replace(r'^(Denver|Austin)$', 'West')

| id |  city  | age |
| -: | -----: | --: |
|  1 |   West |  34 |
|  2 |   West |  52 |
|  3 | Boston |  27 |

%% daf rows=3; cols=3; keyfield='id'; name=''

>>> daf.col('city')
['West', 'West', 'Boston']

replace_in_columns

replace_in_columns(
    cols, find_values=None, replacement=_MISSING
)

Replace listed values with another value, in some columns, in place.

A cell is replaced when it equals any value in find_values. A typical use is ['', None] to fill empty cells. Columns may be given by name or by position, or all columns if cols is None. With no find_values nothing happens. The key index is rebuilt if the keyfield may have changed.

Parameters:

Name Type Description Default
cols T_ls | T_li | T_lsi | None

Column names or positions. If None, all columns.

required
find_values List[Any] | None

The values to look for.

None
replacement Any

The value to put in their place. This is required.

_MISSING

Returns:

Type Description
'Daf'

This Daf, which has been changed.

Raises:

Type Description
ValueError

No replacement is given.

KeyError

A column name is not found.

TypeError

A column is neither a name nor a position.

Examples:

Create a small Daf of people:

>>> daf = Daf(cols=['id', 'city', 'age'], lol=[[1, 'Denver', 34], [2, 'Austin', 52], [3, 'Boston', 27]], keyfield='id')
>>> daf

| id |  city  | age |
| -: | -----: | --: |
|  1 | Denver |  34 |
|  2 | Austin |  52 |
|  3 | Boston |  27 |

%% daf rows=3; cols=3; keyfield='id'; name=''

Replace some values in a column:

>>> daf.replace_in_columns(['city'], ['Denver', 'Boston'], 'unknown')

| id |  city   | age |
| -: | ------: | --: |
|  1 | unknown |  34 |
|  2 |  Austin |  52 |
|  3 | unknown |  27 |

%% daf rows=3; cols=3; keyfield='id'; name=''

Sorting

sort_by_colname

sort_by_colname(
    colname,
    *,
    reverse=False,
    length_priority=False,
    as_str=False,
)

Sort the rows by one column, in place.

Make a copy first if you need the original order. An empty cell sorts before a cell with content, unlike a spreadsheet. Values in the column must be comparable with each other. A column that mixes None or text with numbers raises TypeError, which names the column. Use as_str=True to sort by the text of each value instead.

With length_priority, a shorter text sorts before a longer one, so numbers that are stored as text sort as numbers. Without it, '10', '100', '8' are in text order. length_priority needs text, so for real numbers use it with as_str=True. Then whole numbers sort in numeric order, and negative and decimal numbers sort in text order.

Parameters:

Name Type Description Default
colname str

The column to sort by.

required
reverse bool

If True, sort from high to low.

False
length_priority bool

If True, sort by length first, then by value.

False
as_str bool

If True, sort by the text of each value, and None sorts as an empty cell.

False

Returns:

Type Description
'Daf'

This Daf, which has been changed.

Raises:

Type Description
KeyError

The column name is not found.

TypeError

The column holds values that cannot be compared, and as_str is False.

Examples:

Create a small Daf of codes, text of digits:

>>> daf = Daf(cols=['code'], lol=[['10'], ['99'], ['8'], ['100']])
>>> daf

| code |
| ---: |
|   10 |
|   99 |
|    8 |
|  100 |

%% daf rows=4; cols=1; keyfield=''; name=''

Sort with shorter text first, so '8' comes before '10':

>>> daf.sort_by_colname('code', length_priority=True)

| code |
| ---: |
|    8 |
|   10 |
|   99 |
|  100 |

%% daf rows=4; cols=1; keyfield=''; name=''

A column of numbers with None and an empty cell sorts as text, with as_str=True:

>>> daf = Daf(cols=['age'], lol=[[34], [None], [7], ['']])
>>> daf

| age  |
| ---: |
|   34 |
| None |
|    7 |
|      |

%% daf rows=4; cols=1; keyfield=''; name=''

>>> daf.sort_by_colname('age', as_str=True, length_priority=True)

| age  |
| ---: |
| None |
|      |
|    7 |
|   34 |

%% daf rows=4; cols=1; keyfield=''; name=''

From high to low:

>>> stock = Daf(cols=['id', 'qty'], lol=[['a1', 3], ['b2', 1], ['c3', 2]])
>>> stock.sort_by_colname('qty', reverse=True)

| id | qty |
| -: | --: |
| a1 |   3 |
| c3 |   2 |
| b2 |   1 |

%% daf rows=3; cols=2; keyfield=''; name=''

sort_by_colnames

sort_by_colnames(
    colnames,
    reverse=False,
    length_priority=False,
    as_str=False,
)

Sort the rows by several columns, in place.

The first column is the main sort key. The others break ties. See sort_by_colname() for the rules of ordering, for length_priority and for as_str. Calling sort_by_colname() for each column, last column first, gives the same order.

Parameters:

Name Type Description Default
colnames T_ls

The columns to sort by, main key first.

required
reverse bool

If True, sort from high to low.

False
length_priority bool

If True, sort by length first, then by value.

False
as_str bool

If True, sort by the text of each value, and None sorts as an empty cell.

False

Returns:

Type Description
'Daf'

This Daf, which has been changed.

Raises:

Type Description
KeyError

A column name is not found.

TypeError

A column holds values that cannot be compared, and as_str is False.

Examples:

Create a small Daf of people, by floor:

>>> daf = Daf(cols=['floor', 'name'], lol=[[2, 'Ben Okafor'], [1, 'Zoe Hart'], [1, 'Ana Lopez']])
>>> daf

| floor |    name    |
| ----: | ---------: |
|     2 | Ben Okafor |
|     1 |   Zoe Hart |
|     1 |  Ana Lopez |

%% daf rows=3; cols=2; keyfield=''; name=''

Sort by floor, then by name within each floor:

>>> daf.sort_by_colnames(['floor', 'name'])

| floor |    name    |
| ----: | ---------: |
|     1 |  Ana Lopez |
|     1 |   Zoe Hart |
|     2 | Ben Okafor |

%% daf rows=3; cols=2; keyfield=''; name=''

The options, on a column of names:

>>> names = Daf(cols=['id', 'name'], lol=[['p1', 'Bea'], ['p2', 'Al'], ['p3', 'Cyrus'], ['p4', 'Bo']])
>>> names.sort_by_colnames(['name'])

| id | name  |
| -: | ----: |
| p2 |    Al |
| p1 |   Bea |
| p4 |    Bo |
| p3 | Cyrus |

%% daf rows=4; cols=2; keyfield=''; name=''

>>> names.sort_by_colnames(['name'], reverse=True)

| id | name  |
| -: | ----: |
| p3 | Cyrus |
| p4 |    Bo |
| p1 |   Bea |
| p2 |    Al |

%% daf rows=4; cols=2; keyfield=''; name=''

With length_priority=True, shorter values come first, and values of one length by value:

>>> names.sort_by_colnames(['name'], length_priority=True)

| id | name  |
| -: | ----: |
| p2 |    Al |
| p4 |    Bo |
| p1 |   Bea |
| p3 | Cyrus |

%% daf rows=4; cols=2; keyfield=''; name=''

A column of numbers mixed with text, or with None, cannot be compared, and raises TypeError. With as_str=True it sorts by text, where '10' comes before '9', and None sorts as an empty cell:

>>> mixed = Daf(cols=['id', 'qty'], lol=[['o1', 10], ['o2', 9], ['o3', 'n/a'], ['o4', None]])
>>> mixed.sort_by_colnames(['qty'], as_str=True)

| id | qty  |
| -: | ---: |
| o4 | None |
| o1 |   10 |
| o2 |    9 |
| o3 |  n/a |

%% daf rows=4; cols=2; keyfield=''; name=''

Reshaping and splitting

transpose

transpose(
    new_keyfield="", new_cols=None, include_header=False
)

Turn rows into columns and columns into rows.

The result has one row for each column of this Daf. With include_header=True, the first column of the result holds the column names of this Daf, and the names given in new_cols or the default names must then include that column. The default cols are A, B and so on, one for each row of this Daf. With include_header=True they start with key. If you pass new_cols, give one name for each row of this Daf, plus one with include_header. The data is copied.

Parameters:

Name Type Description Default
new_keyfield str

The keyfield of the result.

''
new_cols T_la | None

The cols of the result.

None
include_header bool

If True, the column names become the first column.

False

Every row must be as long as the columns. Check with is_rectangular(), and pad short rows with force_rectangular().

Returns:

Type Description
'Daf'

The new Daf.

Raises:

Type Description
ValueError

A row is not as long as the columns.

Examples:

Create a small Daf of people:

>>> daf = Daf(cols=['id', 'name'], lol=[[1, 'Ana Lopez'], [2, 'Ben Okafor']])
>>> daf

| id |    name    |
| -: | ---------: |
|  1 |  Ana Lopez |
|  2 | Ben Okafor |

%% daf rows=2; cols=2; keyfield=''; name=''

Turn the rows into columns, with the column names as the first column:

>>> daf.transpose(include_header=True)

| key  |     A     |     B      |
| ---: | --------: | ---------: |
|   id |         1 |          2 |
| name | Ana Lopez | Ben Okafor |

%% daf rows=2; cols=3; keyfield=''; name=''

>>> daf.transpose().columns()
['A', 'B']
>>> daf.transpose(include_header=True).columns()
['key', 'A', 'B']

Name the columns of the result, and choose its keyfield. Here the first column holds the old column names, so they become the keys:

>>> stock = Daf(cols=['id', 'item', 'qty'], lol=[['a1', 'pen', 3], ['b2', 'ink', 10]])
>>> by_field = stock.transpose(include_header=True, new_cols=['field', 'a1', 'b2'], new_keyfield='field')
>>> by_field

| field | a1  | b2  |
| ----: | --: | --: |
|    id |  a1 |  b2 |
|  item | pen | ink |
|   qty |   3 |  10 |

%% daf rows=3; cols=3; keyfield='field'; name=''

>>> by_field.select_record('qty')
{'field': 'qty', 'a1': 3, 'b2': 10}

wide_to_narrow

wide_to_narrow(
    id_cols,
    varname_colname="variable",
    value_colname="value",
)

Turn columns into rows. This is called melt or unpivot.

Each column that is not an id column gives one row for each row of this Daf. The row holds the id values, the name of the column, and its value.

The default names, variable and value, are those that narrow_to_wide() reads, and those that pandas melt() uses. So the two methods chain with their defaults.

Parameters:

Name Type Description Default
id_cols T_ls

The columns that identify a row. They are kept as they are.

required
varname_colname str

The name of the new column that holds the old column names.

'variable'
value_colname str

The name of the new column that holds the values.

'value'

Returns:

Type Description
'Daf'

The new Daf.

Raises:

Type Description
TypeError

id_cols is not a list.

Examples:

Create a small Daf of sales by city, one column for each quarter:

>>> daf = Daf(cols=['city', 'q1', 'q2'], lol=[['Denver', 1200, 1450], ['Austin', 980, 1105]])
>>> daf

|  city  |  q1  |  q2  |
| -----: | ---: | ---: |
| Denver | 1200 | 1450 |
| Austin |  980 | 1105 |

%% daf rows=2; cols=3; keyfield=''; name=''

Turn it into one row for each city and quarter:

>>> daf.wide_to_narrow(['city'])

|  city  | variable | value |
| -----: | -------: | ----: |
| Denver |       q1 |  1200 |
| Denver |       q2 |  1450 |
| Austin |       q1 |   980 |
| Austin |       q2 |  1105 |

%% daf rows=4; cols=3; keyfield=''; name=''

A round trip:

>>> daf.wide_to_narrow(['city']).narrow_to_wide(['city']).lol
[['Denver', 1200, 1450], ['Austin', 980, 1105]]

Name the two new columns:

>>> sales = Daf(cols=['store', 'apples', 'pears'], lol=[['s1', 30, 12], ['s2', 25, 40]])
>>> sales.wide_to_narrow(['store'], varname_colname='item', value_colname='qty')

| store |  item  | qty |
| ----: | -----: | --: |
|    s1 | apples |  30 |
|    s1 |  pears |  12 |
|    s2 | apples |  25 |
|    s2 |  pears |  40 |

%% daf rows=4; cols=3; keyfield=''; name=''

narrow_to_wide

narrow_to_wide(
    id_cols,
    varname_col="variable",
    value_col="value",
    wide_cols=None,
)

Turn rows into columns. This is called pivot or spread.

The rows of one id may be anywhere in the table. The result has one row for each id, in the order in which the ids first appear. The columns are the id columns and then the names found in varname_col, in the order first seen. An id that has no value for a name gets NULL. If an id has the same name more than once, the last value is kept.

With wide_cols, those are the columns after the ids, in that order. A name that is not listed is left out.

The default names, variable and value, are those that wide_to_narrow() writes.

An empty Daf gives an empty Daf.

Parameters:

Name Type Description Default
id_cols T_cs

The columns that identify a row.

required
varname_col str

The column whose values become the new column names.

'variable'
value_col str

The column whose values fill the new columns.

'value'
wide_cols T_cs | None

The names to use as columns, in order. If None, all names found.

None

Returns:

Type Description
'Daf'

The new Daf.

Examples:

Create a small Daf of sales, one row for each city and quarter:

>>> daf = Daf(cols=['city', 'variable', 'value'], lol=[['Denver', 'q1', 1200], ['Austin', 'q1', 980], ['Denver', 'q2', 1450], ['Austin', 'q2', 1105]])
>>> daf

|  city  | variable | value |
| -----: | -------: | ----: |
| Denver |       q1 |  1200 |
| Austin |       q1 |   980 |
| Denver |       q2 |  1450 |
| Austin |       q2 |  1105 |

%% daf rows=4; cols=3; keyfield=''; name=''

Turn it into one row for each city, with a column for each quarter. Choose the columns and their order with wide_cols:

>>> daf.narrow_to_wide(['city'])

|  city  |  q1  |  q2  |
| -----: | ---: | ---: |
| Denver | 1200 | 1450 |
| Austin |  980 | 1105 |

%% daf rows=2; cols=3; keyfield=''; name=''

>>> daf.narrow_to_wide(['city'], wide_cols=['q2', 'q1'])

|  city  |  q2  |  q1  |
| -----: | ---: | ---: |
| Denver | 1450 | 1200 |
| Austin | 1105 |  980 |

%% daf rows=2; cols=3; keyfield=''; name=''

Name the two columns to read, and keep only some of the new columns:

>>> narrow = Daf(cols=['store', 'item', 'qty'], lol=[
...     ['s1', 'apples', 30], ['s1', 'pears', 12], ['s2', 'apples', 25], ['s2', 'pears', 40]])
>>> narrow.narrow_to_wide(['store'], varname_col='item', value_col='qty')

| store | apples | pears |
| ----: | -----: | ----: |
|    s1 |     30 |    12 |
|    s2 |     25 |    40 |

%% daf rows=2; cols=3; keyfield=''; name=''

>>> narrow.narrow_to_wide(['store'], varname_col='item', value_col='qty', wide_cols=['pears'])

| store | pears |
| ----: | ----: |
|    s1 |    12 |
|    s2 |    40 |

%% daf rows=2; cols=2; keyfield=''; name=''

split_daf_into_ranges

split_daf_into_ranges(chunk_ranges)

Split the rows into several Daf instances, by position ranges.

Each range is (start, end), and end is not included. The new Daf instances share their rows with this one.

Parameters:

Name Type Description Default
chunk_ranges List[Tuple[int, int]]

The ranges of row positions.

required

Returns:

Type Description
List['Daf']

A list of Daf instances, one for each range.

Examples:

Create a small Daf of people:

>>> daf = Daf(cols=['id', 'city', 'age'], lol=[[1, 'Denver', 34], [2, 'Austin', 52], [3, 'Boston', 27]], keyfield='id')
>>> daf

| id |  city  | age |
| -: | -----: | --: |
|  1 | Denver |  34 |
|  2 | Austin |  52 |
|  3 | Boston |  27 |

%% daf rows=3; cols=3; keyfield='id'; name=''

Split it into two Daf objects, by ranges of rows:

>>> parts = daf.split_daf_into_ranges([(0, 2), (2, 3)])
>>> parts[0]

| id |  city  | age |
| -: | -----: | --: |
|  1 | Denver |  34 |
|  2 | Austin |  52 |

%% daf rows=2; cols=3; keyfield='id'; name=''

>>> parts[1]

| id |  city  | age |
| -: | -----: | --: |
|  3 | Boston |  27 |

%% daf rows=1; cols=3; keyfield='id'; name=''

split_daf_into_chunks_lodaf

split_daf_into_chunks_lodaf(max_chunk_size)

Split the rows evenly into Daf instances of at most a given size.

The sizes are as equal as possible, so some chunks are smaller than the maximum. None is larger. The chunks share their rows with this Daf.

Parameters:

Name Type Description Default
max_chunk_size int

The most rows in one chunk.

required

Returns:

Type Description
List['Daf']

A list of Daf instances.

Examples:

Create a Daf of seven order numbers:

>>> daf = Daf(cols=['order_no'], lol=[[1001 + i] for i in range(7)])
>>> daf

| order_no |
| -------: |
|     1001 |
|     1002 |
|     1003 |
|     1004 |
|     1005 |
|     1006 |
|     1007 |

%% daf rows=7; cols=1; keyfield=''; name=''

Split it into chunks of at most three rows:

>>> [len(part) for part in daf.split_daf_into_chunks_lodaf(3)]
[3, 2, 2]