Skip to content

Selecting and indexing

Reading rows, columns and cells by index, key, or condition.

Indexing with brackets

__getitem__

__getitem__(slice_spec)

Select rows, columns or cells, as in my_daf[rows, cols].

The selector is [rows] or [rows, cols]. With one selector, all columns are returned. Use : for all. A selector is one of these.

integer       A position. Negative counts from the end.
slice         `2:5`, `:3`, `::2`, as for a Python list.
list          A list of positions, in the order given, or a list of ranges.
range         A range of positions.
string        A key of the keyfield for rows, or a column name for columns.
list of str   Several keys, or several column names, in the order given.
tuple         An inclusive range of keys, or of column names. Use None to
              start at the first or to end at the last, as in `(None, 'r3')`.

A tuple of two items is read as [rows, cols] when it stands alone. To give a range of row keys, add the column selector, as in my_daf[('r1', 'r3'), :].

Integers are always positions. A keyfield or column names that are integers cannot be used in brackets. Use select_krows() and select_kcols() instead.

The result is a new Daf. Its rows are shared with this Daf when you select rows, so changing a cell in the result changes it here too. Selecting columns makes new row lists, so replacing a cell in the result does not change this Daf. A list or dict held in a cell is still the same object in both. Use copy('deep') when those must be separate too. The keyfield and dtypes carry over if their columns are still there. See retmode for getting a bare value or list when the result is one cell, row or column.

A column slice works as it does for a Python list.

Parameters:

Name Type Description Default
slice_spec slice | int | str | T_li | T_ls | range | T_lor | Tuple[slice | int | str | T_li | T_ls | range | T_lor | Tuple[str, str], slice | int | str | T_li | T_ls | range | T_lor | Tuple[str, str]]

A row selector, or a tuple of a row selector and a column selector.

required

Returns:

Type Description
Any

A new Daf, or a value or list if retmode is val.

Raises:

Type Description
IndexError

A row or column position is out of range.

KeyError

A key or column name is not found.

KeysDisabledError

Rows are selected by key and there is no keyfield.

TypeError

A selector is None, or has a type that is not accepted.

Examples:

The table used in the examples, with text keys in id:

>>> daf = Daf(cols=['id', 'item', 'qty'], keyfield='id', lol=[
...     ['a1', 'pen', 3], ['b2', 'ink', 10], ['c3', 'pad', 7], ['d4', 'cap', 1]])

Rows by position. A number is a position from 0, and a negative one counts from the end:

>>> daf[1]

| id | item | qty |
| -: | ---: | --: |
| b2 |  ink |  10 |

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

>>> daf[-1]

| id | item | qty |
| -: | ---: | --: |
| d4 |  cap |   1 |

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

A slice, a list of positions in the order given, or a range:

>>> daf[1:3]

| id | item | qty |
| -: | ---: | --: |
| b2 |  ink |  10 |
| c3 |  pad |   7 |

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

>>> daf[[3, 0]]

| id | item | qty |
| -: | ---: | --: |
| d4 |  cap |   1 |
| a1 |  pen |   3 |

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

>>> daf[range(0, 4, 2)]

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

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

Rows by key. A string is a key, and a list of strings gives several keys, in that order:

>>> daf['c3']

| id | item | qty |
| -: | ---: | --: |
| c3 |  pad |   7 |

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

>>> daf[['d4', 'a1']]

| id | item | qty |
| -: | ---: | --: |
| d4 |  cap |   1 |
| a1 |  pen |   3 |

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

A tuple of two keys is an inclusive range, in the order of the table. It needs the column part, :, so it is not read as [rows, cols]. None as an end means the start or the end:

>>> daf[('b2', 'c3'), :]

| id | item | qty |
| -: | ---: | --: |
| b2 |  ink |  10 |
| c3 |  pad |   7 |

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

>>> daf[('c3', None), :]

| id | item | qty |
| -: | ---: | --: |
| c3 |  pad |   7 |
| d4 |  cap |   1 |

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

Columns. The second part selects columns, by name, by a list of names, or by position:

>>> daf[:, 'qty']

| qty |
| --: |
|   3 |
|  10 |
|   7 |
|   1 |

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

>>> daf[:, ['qty', 'id']]

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

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

>>> daf[:, 1:]

| item | qty |
| ---: | --: |
|  pen |   3 |
|  ink |  10 |
|  pad |   7 |
|  cap |   1 |

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

Rows and columns together, and one cell, read as a value:

>>> daf[['a1', 'c3'], ['id', 'qty']]

| id | qty |
| -: | --: |
| a1 |   3 |
| c3 |   7 |

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

>>> daf['b2', 'qty'].to_value()
10

Selections share their rows. A change through a selection of rows shows in the table:

>>> some = daf[0:2]
>>> some['a1', 'qty'] = 30
>>> daf

| id | item | qty |
| -: | ---: | --: |
| a1 |  pen |  30 |
| b2 |  ink |  10 |
| c3 |  pad |   7 |
| d4 |  cap |   1 |

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

A key or name that is not there raises KeyError:

>>> daf['z9']
Traceback (most recent call last):
...
KeyError: 'z9'

__setitem__

__setitem__(slice_spec, value)

Assign values to a selection, as in my_daf[rows, cols] = value.

The selector is the same as for []. The Daf is changed in place.

A single value fills every cell of the selection. A list fills the selection in order. A dict given for a row sets that row from the dict. The cells whose columns are not in the dict become NULL. See set_irows_icols() for what happens when the source and the selection differ in size.

A str or bytes is one value, not a list of characters, so my_daf[:, 'v'] = 'xyz' sets every row of v to xyz. A list assigned to several whole rows is copied, so each row has its own list.

A write does not update the key index (kd). Writing into a keyfield cell, or writing a whole row, which includes the key, leaves the kd as it was: a lookup still finds the row by its old key, and not by the new one. So don't change keys this way. If you must, call set_keyfield() with the same keyfield afterwards, which invalidates the kd, so it is rebuilt when it is next needed. Writing other columns is safe.

A selection that shares the row has a key index of its own. Resetting one Daf does not reset the other. Call set_keyfield() on each Daf that will look up keys.

A single name, as in my_daf['x'] = value, selects the row with that key. It is not a column, as it would be in pandas. Use my_daf[:, 'x'] for a column, or assign_col() to add one. A name that is not a row key raises an error that says this.

Parameters:

Name Type Description Default
slice_spec slice | int | str | range | T_li | T_ls | T_lb | T_lor | Tuple[slice | int | str | range | T_lor | T_li | T_ls | T_lb | Tuple[Any, Any], slice | int | str | range | T_lor | T_li | T_ls | T_lb | Tuple[Any, Any]]

A row selector, or a tuple of a row selector and a column selector.

required
value Any

The value, list, dict or Daf to assign.

required

Raises:

Type Description
KeyError

A row key or a column name is not found.

KeysDisabledError

A row is selected by key, and the Daf has no keyfield.

Examples:

The table used in the examples, with text keys in id:

>>> daf = Daf(cols=['id', 'item', 'qty'], keyfield='id', lol=[
...     ['a1', 'pen', 3], ['b2', 'ink', 10], ['c3', 'pad', 7]])

One cell, by key and column name, or by positions:

>>> daf['b2', 'qty'] = 12
>>> daf[0, 'item'] = 'pens'
>>> daf

| id | item | qty |
| -: | ---: | --: |
| a1 | pens |   3 |
| b2 |  ink |  12 |
| c3 |  pad |   7 |

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

A column, from a list with one value for each row, or from one value for every row. A string is one value, not a list of characters:

>>> daf[:, 'qty'] = [4, 5, 6]
>>> daf[:, 'item'] = 'misc'
>>> daf

| id | item | qty |
| -: | ---: | --: |
| a1 | misc |   4 |
| b2 | misc |   5 |
| c3 | misc |   6 |

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

A row, from a list in column order, or from a dict by column name. A dict sets the columns it lacks to NULL, the empty string:

>>> daf['c3'] = ['c3', 'pad', 7]
>>> daf['a1'] = {'id': 'a1', 'qty': 1}
>>> daf

| id | item | qty |
| -: | ---: | --: |
| a1 |      |   1 |
| b2 | misc |   5 |
| c3 |  pad |   7 |

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

Several rows and columns, from one value:

>>> daf[['a1', 'b2'], ['item']] = 'pen'
>>> daf

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

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

Keys. A write does not update the index of keys. After changing a key, call set_keyfield() before looking the row up by its new key:

>>> daf['c3', 'id'] = 'c9'
>>> daf.select_record('c9')
{}
>>> daf.set_keyfield(daf.keyfield).select_record('c9')
{'id': 'c9', 'item': 'pad', 'qty': 7}

set_irows_icols

set_irows_icols(irows, icols, value)

Set values at row positions and column positions, in place.

This is what my_daf[rows, cols] = value calls, after the selectors are turned into positions. irows and icols are an integer, a slice, a range or a list. If icols is None, the whole row is set. If irows is None, nothing is set. Use slice(None) for all rows.

What is set depends on the value.

a single value    fills every selected cell. A str or bytes is a single value.
a list            fills a selection in order. For several whole rows, each
                  row becomes a copy of the list.
a dict            sets a row. The cells of columns that the dict lacks become NULL.
a Daf             is copied as a block, from its top left corner.

Nothing is checked, and no error is raised for a size mismatch. A smaller source fills the top left of the selection and leaves the rest. A larger one fills the selection and the extra values are ignored. Check the sizes first if it matters.

Parameters:

Name Type Description Default
irows slice | int | range | T_li | Iterable | None

The row positions.

required
icols slice | int | range | T_li | None

The column positions.

required
value Any

The value, list, dict or Daf to set.

required

Returns:

Type Description
'Daf'

This Daf, which has been changed.

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]])
>>> daf

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

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

Set the city and age of the first two rows to one value:

>>> daf.set_irows_icols([0, 1], [1, 2], 'unknown')

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

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

Set a whole row from a list, with None for every column:

>>> daf.set_irows_icols(2, None, [4, 'Miami', 60])

| id |  city   |   age   |
| -: | ------: | ------: |
|  1 | unknown | unknown |
|  2 | unknown | unknown |
|  4 |   Miami |      60 |

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

Rows

select_krows

select_krows(krows, inverse=False, silent_error=False)

Select rows by key. Rows with those keys are kept, or dropped if inverse is True.

This is the same as my_daf[keys], with a choice to drop rows and to ignore keys that are not found. It works with integer keys, which brackets cannot. The result is a new Daf with its own outer row list. Each row is the same list as in this Daf. Use copy('editable') before changing cells in one without the other.

A bare tuple means an inclusive range of keys, so (1, 2) is the rows from key 1 through key 2. For a composite keyfield, give a list of tuples.

Parameters:

Name Type Description Default
krows slice | str | T_la | int | T_lota | Tuple[Any, Any] | Iterable | None

A key, a list of keys, or a tuple that gives a range of keys.

required
inverse bool

If True, drop the selected rows and keep the others.

False
silent_error bool

If True, keys that are not found are ignored.

False

Returns:

Type Description
'Daf'

The new Daf.

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 an int id. An int here is a key, not a position:

>>> 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=''

Select the rows with keys 3 and 1, in that order:

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

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

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

Select the rows not listed:

>>> daf.select_krows([1, 2], inverse=True)

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

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

Leave out a key that is not found:

>>> daf.select_krows([1, 9], silent_error=True)

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

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

select_irows

select_irows(irows, inverse=False, invert=False)

Select rows by position. Those rows are kept, or dropped if inverse is True.

This is the same as my_daf[rows], with a choice to drop rows. It is cheap. The result is a new Daf with its own outer row list. Each row is the same list as in this Daf, so changing a cell in the result changes it here too. This is also so when the selection is empty and inverse is True, which keeps all the rows. The keyfield, dtypes and column names carry over.

Parameters:

Name Type Description Default
irows slice | int | T_li | range | T_lor | Iterable | None

A position, a slice, a range, a list of positions, or a list of ranges.

required
inverse bool

If True, drop the selected rows and keep the others.

False
invert bool

The old name of inverse, still accepted.

False

Returns:

Type Description
'Daf'

The new Daf.

Raises:

Type Description
IndexError

A single position is out of 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=''

Select the row at position 1, and every row but that one:

>>> daf.select_irows(1)

| id |  city  | age |
| -: | -----: | --: |
|  2 | Austin |  52 |

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

>>> daf.select_irows(1, inverse=True)

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

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

>>> daf.select_irows(1, invert=True)

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

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

Select a slice of rows:

>>> daf.select_irows(slice(1, None))

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

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

irow

irow(irow=0, include_cols=None)

Get one row as a dict, by position.

This is iloc() with the default rtype. A negative position counts from the end. The dict is new, so changing it does not change the Daf.

Parameters:

Name Type Description Default
irow int

The row position.

0
include_cols T_ls | None

Only these columns are included.

None

Returns:

Type Description
T_da

The row as a dict. A negative position counts from the end. A Daf with no rows

T_da

gives an empty dict.

Raises:

Type Description
IndexError

The position is out of range, 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=''

Read the row at position 1 as a dict, with only some columns:

>>> daf.irow(1, include_cols=['age'])
{'age': 52}

irow_la

irow_la(irow)

Get one row as a list, by position.

The list is the row itself, not a copy. Changing it changes the Daf. Use iloc() with rtype='list' for a copy.

Parameters:

Name Type Description Default
irow int

The row position.

required

Returns:

Type Description
T_la

The row.

Raises:

Type Description
IndexError

The position is out of range.

Examples:

Create a small Daf of people:

>>> daf = Daf(cols=['id', 'city', 'age'], lol=[['p1', 'Denver', 34], ['p2', 'Austin', ''], ['p3', 'Denver', 27]], keyfield='id')
>>> daf

| id |  city  | age |
| -: | -----: | --: |
| p1 | Denver |  34 |
| p2 | Austin |     |
| p3 | Denver |  27 |

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

Read the row at position 1, as the Daf's own list:

>>> daf.irow_la(1)
['p2', 'Austin', '']
>>> row = daf.irow_la(0)
>>> row[1] = 'Miami'
>>> daf

| id |  city  | age |
| -: | -----: | --: |
| p1 |  Miami |  34 |
| p2 | Austin |     |
| p3 | Denver |  27 |

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

>>> daf.irow_la(9)
Traceback (most recent call last):
    ...
IndexError: list index out of range

iloc

iloc(
    irow: int = 0,
    include_cols: T_ls | None = None,
    rtype: Literal["dict"] = "dict",
) -> T_da
iloc(
    irow: int = 0,
    include_cols: T_ls | None = None,
    *,
    rtype: Literal["klist"],
) -> KeyedList
iloc(
    irow: int = 0,
    include_cols: T_ls | None = None,
    *,
    rtype: Literal["list"],
) -> T_la
iloc(
    irow: int = 0,
    include_cols: T_ls | None = None,
    rtype: str = "dict",
) -> T_ma | T_la
iloc(irow=0, include_cols=None, rtype='dict')

Get one row by position, as a dict, a KeyedList or a list.

A negative position counts from the end, so -1 is the last row. A position that is out of range raises IndexError. A Daf with no rows, and a row with no cells, give an empty dict, or an empty KeyedList. A dict or a KeyedList needs column names, so a Daf that has rows and no column names raises KeysDisabledError. Name them with set_cols(), or ask for rtype='list'.

Parameters:

Name Type Description Default
irow int

The row position.

0
include_cols T_ls | None

Only these columns are included. This applies to a dict.

None
rtype str

dict for a new dict, klist for a KeyedList that shares the row, or list for a copy of the row.

'dict'

Returns:

Type Description
T_ma | T_la

The row.

Raises:

Type Description
IndexError

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

KeysDisabledError

rtype is dict or klist, and the Daf has rows and no column names.

ValueError

rtype is not one of the three names.

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=''

Read the row at position 1 as a dict, as a list, and the last row:

>>> daf.iloc(1)
{'id': 2, 'city': 'Austin', 'age': 52}
>>> daf.iloc(1, rtype='list')
[2, 'Austin', 52]
>>> daf.iloc(-1)
{'id': 3, 'city': 'Boston', 'age': 27}

Only some columns, in a dict:

>>> daf.iloc(1, include_cols=['id', 'age'])
{'id': 2, 'age': 52}

A KeyedList shares the row with the Daf, so a change to it changes the table:

>>> row = daf.iloc(1, rtype='klist')
>>> row['age'] = 35
>>> daf

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

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

select_record

select_record(key, silent_error=True)

Get one row as a dict, by its key.

If the key is not found, the answer is an empty dict, unless silent_error is False. Then a KeyError is raised. A typo in a key gives an empty dict, so check it, or pass silent_error=False. An empty Daf gives an empty dict. For a composite keyfield the key is a tuple.

Parameters:

Name Type Description Default
key str | int | T_ta

The key of the row.

required
silent_error bool

If False, raise an error when the key is not found.

True

Returns:

Type Description
T_da

The row as a dict, or an empty dict.

Raises:

Type Description
KeysDisabledError

The Daf has rows but 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 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=''

Read the row with key 2 as a dict:

>>> daf.select_record(2)
{'id': 2, 'city': 'Austin', 'age': 52}
>>> daf.select_record(9)
{}

A key that is not found gives an empty dict, quietly. Pass silent_error=False to raise instead:

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

select_records

select_records(keys_ls, inverse=False, silent_error=False)

Select several rows by key and return them as a Daf.

This is select_krows() with a friendlier answer for an empty list of keys. No keys gives an empty Daf, or all the rows if inverse is True.

The keys may be another Daf. Its keys are then used, through a view of its key index, so no list of them is made. That other Daf must have a keyfield. Its rows are not changed. The keys come in the order of its key index, so the rows selected come in that order too. A key that repeats in this Daf selects only its last row. See keys().

select_records_daf() is the old name of this method. It still works, and is deprecated.

The rows are shared with this Daf, as in select_krows(). The new Daf has its own row list, also with no keys and inverse True, so adding a row to one does not add it to the other.

Parameters:

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

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

required
inverse bool

If True, drop the selected rows and keep the others.

False
silent_error bool

If True, keys that are not found are ignored.

False

Returns:

Type Description
'Daf'

The new Daf.

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.

Examples:

Create a small Daf of people, keyed by id. One age is not known:

>>> daf = Daf(cols=['id', 'city', 'age'], lol=[['p1', 'Denver', 34], ['p2', 'Austin', ''], ['p3', 'Denver', 27]], keyfield='id')
>>> daf

| id |  city  | age |
| -: | -----: | --: |
| p1 | Denver |  34 |
| p2 | Austin |     |
| p3 | Denver |  27 |

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

Select the rows with these keys, in the order given. No keys selects no rows:

>>> daf.select_records(['p3', 'p1'])

| id |  city  | age |
| -: | -----: | --: |
| p3 | Denver |  27 |
| p1 | Denver |  34 |

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

>>> daf.select_records([])


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

>>> kept = daf.select_records([], inverse=True)
>>> kept == daf
True
>>> kept.append(['p4', 'Boston', 41])

| id |  city  | age |
| -: | -----: | --: |
| p1 | Denver |  34 |
| p2 | Austin |     |
| p3 | Denver |  27 |
| p4 | Boston |  41 |

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

>>> daf.num_rows(), kept.num_rows()
(3, 4)
>>> kept[0, 'city'] = 'Miami'
>>> daf

| id |  city  | age |
| -: | -----: | --: |
| p1 |  Miami |  34 |
| p2 | Austin |     |
| p3 | Denver |  27 |

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

The keys of another Daf, without making a list of them:

>>> other = Daf(cols=['id', 'visits'], lol=[['p3', 7], ['p9', 12]], keyfield='id')
>>> other

| id | visits |
| -: | -----: |
| p3 |      7 |
| p9 |     12 |

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

>>> daf.select_records(other, silent_error=True).to_lod()
[{'id': 'p3', 'city': 'Denver', 'age': 27}]

Columns

select_kcols

select_kcols(
    kcols, inverse=False, flip=False, silent_error=False
)

Select columns by name. Columns with those names are kept, or dropped if inverse is True.

This is the same as my_daf[:, names], with more choices. The result is a new Daf with new rows, in the order of the names you give. With flip=True the selected columns become rows, and the result has no column names and no keyfield. This costs no more than selecting the columns.

Selecting columns copies data, so it is not cheap. For apply and reduce, use their cols argument instead.

Parameters:

Name Type Description Default
kcols slice | str | T_la | int | Tuple[Any, Any] | None

A name, a list of names, or a tuple that gives a range of names.

required
inverse bool

If True, drop the named columns and keep the others.

False
flip bool

If True, turn the selected columns into rows.

False
silent_error bool

If True, names that are not found are ignored.

False

Returns:

Type Description
'Daf'

The new Daf.

Raises:

Type Description
KeysDisabledError

The Daf has no column names.

KeyError

A name is not found and silent_error is False.

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=''

Select two columns by name, in the order given:

>>> daf.select_kcols(['age', 'id'])

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

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

Select every column but one:

>>> daf.select_kcols('city', inverse=True).columns()
['id', 'age']

Select a column and turn it into a row, with flip=True:

>>> daf.select_kcols('city', flip=True)

|   A    |   B    |   C    |
| -----: | -----: | -----: |
| Denver | Austin | Boston |

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

A name that is not a column raises KeyError, or is left out with silent_error=True:

>>> daf.select_kcols(['id', 'email'], silent_error=True).columns()
['id']

select_icols

select_icols(icols, flip=False)

Select columns by position. Those columns are kept, in the order given.

This is the same as my_daf[:, cols]. It makes new rows, so it is not cheap. For apply and reduce, use their cols argument instead. A slice works as it does for a Python list. The keyfield and dtypes carry over if their columns are kept. With flip=True the columns become rows, and the result has no column names, no dtypes and no keyfield.

With flip=True the columns are turned into rows as they are selected. That costs less than selecting them and then calling transpose(). In one test with 5 of 50 columns and 20,000 rows it took 0.003 s, against 0.034 s.

Parameters:

Name Type Description Default
icols slice | int | T_li | range | T_lor | None

A position, a slice, a range, a list of positions, or a list of ranges.

required
flip bool

If True, turn the selected columns into rows.

False

Returns:

Type Description
'Daf'

The new Daf.

Raises:

Type Description
IndexError

A position is beyond the end of some 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=''

Select columns by position, in the order given:

>>> daf.select_icols([2, 0])

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

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

Select the last two columns:

>>> daf.select_icols(slice(-2, None)).columns()
['city', 'age']

Select two columns and turn them into rows, with flip=True:

>>> daf.select_icols([0, 1], flip=True)

|   A    |   B    |   C    |
| -----: | -----: | -----: |
|      1 |      2 |      3 |
| Denver | Austin | Boston |

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

select_cols

select_cols(cols=None, exclude_cols=None)

Make a new Daf with only some columns, chosen by name.

The columns come in the order of cols, as with select_kcols() and my_daf[:, cols]. A name given twice is used once. A name that is not a column raises KeyError. With no cols, all columns are kept, in the order of this Daf. Then exclude_cols leaves out the columns you name. A name in exclude_cols that is not a column is ignored.

This copies data, so it is not cheap. For apply and reduce, use their cols argument instead. The keyfield carries over if its column is kept. A Daf with no column names gives rows with no columns.

Parameters:

Name Type Description Default
cols T_ls | None

The names of the columns to keep, in the order you want. If empty, all columns.

None
exclude_cols T_ls | None

The names of the columns to leave out.

None

Returns:

Type Description
'Daf'

The new Daf.

Raises:

Type Description
KeyError

A name in cols is not a column.

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=''

Select some columns, in the order given, or every column but some:

>>> daf.select_cols(['age', 'id']).columns()
['age', 'id']
>>> daf.select_cols(exclude_cols=['city']).columns()
['id', 'age']

col

col(
    colname,
    *,
    unique=False,
    omit_nulls=False,
    silent_error=False,
    astype=None,
    indirect_col=None,
    default="",
)

Get one column as a list, by name.

This reads the column directly, without making a Daf first, as daf[:, 'v'].to_list() does. So it is the fast way to get the values of one column.

The options leave values out or change them:

  • unique=True keeps the first of each value, in order.
  • omit_nulls=True leaves out NULL, the empty string.
  • astype converts each value with a type or a function.
  • silent_error=True gives an empty list for a column that does not exist, where it would raise.

indirect_col is for sparse data, where each row holds a dict in one column, with only the keys it has. Then colname is a key of those dicts, and a row that lacks it gets default. A name that is a real column is still read from the column.

Parameters:

Name Type Description Default
colname str

The column name.

required
unique bool

If True, leave out repeated values and keep the order.

False
omit_nulls bool

If True, leave out the empty values.

False
silent_error bool

If True, a column that is not found gives an empty list.

False
astype Callable | str | type | None

A type or function to convert each value with.

None
indirect_col str | None

A column that holds a dict, to read the name from.

None
default Any | None

The value for a row that lacks the name. It is used only with indirect_col.

''

Returns:

Type Description
list

The values of the column.

Raises:

Type Description
ColumnNotFoundError

The column is not found and silent_error is False. This is a KeyError, and also a RuntimeError, so a handler for either catches it.

RuntimeError

The name is empty.

Examples:

Create a small Daf of customers, with a plan and a cart of items for each. One plan is not known:

>>> daf = Daf(cols=['id', 'plan', 'cart'], keyfield='id', lol=[
...     ['c1', 'basic', {'apples': 1}],
...     ['c2', 'pro', {'apples': 1, 'pears': 2}],
...     ['c3', '',  {}],
...     ['c4', 'basic', {'pears': 1}]])
>>> daf.col('plan')
['basic', 'pro', '', 'basic']

Each value once, and without the empty ones:

>>> daf.col('plan', unique=True)
['basic', 'pro', '']
>>> daf.col('plan', omit_nulls=True)
['basic', 'pro', 'basic']
>>> daf.col('plan', unique=True, omit_nulls=True)
['basic', 'pro']

Convert each value, here with a function:

>>> daf.col('id', astype=str.upper)
['C1', 'C2', 'C3', 'C4']

A column that does not exist raises, or gives an empty list:

>>> daf.col('email')
Traceback (most recent call last):
...
daffodil.daf.ColumnNotFoundError: 'email'
>>> daf.col('email', silent_error=True)
[]

Read a key from the dict in the cart column. A row without it gets NULL, or default:

>>> daf.col('apples', indirect_col='cart')
[1, 1, '', '']
>>> daf.col('pears', indirect_col='cart', default=0)
[0, 2, 0, 1]

col_to_la

col_to_la(
    colname,
    *,
    unique=False,
    omit_nulls=False,
    silent_error=False,
    astype=None,
    indirect_col=None,
    default="",
)

Get one column as a list, by name.

This does the same as col(), which shows each option.

Parameters:

Name Type Description Default
colname str

The column name.

required
unique bool

If True, leave out repeated values and keep the order.

False
omit_nulls bool

If True, leave out the empty values.

False
silent_error bool

If True, a column that is not found gives an empty list.

False
astype Callable | str | type | None

A type or function to convert each value with.

None
indirect_col str | None

A column that holds a dict, to read the name from.

None
default Any | None

The value for a row that lacks the name. It is used only with indirect_col.

''

Returns:

Type Description
list

The values of the column.

Raises:

Type Description
ColumnNotFoundError

The column is not found and silent_error is False. This is a KeyError, and also a RuntimeError, so a handler for either catches it.

RuntimeError

The name is empty.

Examples:

col_to_la() is the same method as col(), which has an example

of each option:

>>> daf = Daf(cols=['id', 'plan'], lol=[['c1', 'basic'], ['c2', 'pro'], ['c3', 'basic']])
>>> daf.col_to_la('plan', unique=True) == daf.col('plan', unique=True)
True

icol

icol(icol)

Get one column as a list, by position.

A negative position counts from the end, so -1 is the last column. A position that is out of range raises IndexError. A Daf with no rows gives an empty list.

Parameters:

Name Type Description Default
icol int

The column position.

required

Returns:

Type Description
list

The values of the column.

Raises:

Type Description
IndexError

The position is out of range, 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=''

Read the column at position 1, and the last column:

>>> daf.icol(1)
['Denver', 'Austin', 'Boston']
>>> daf.icol(-1)
[34, 52, 27]

icol_to_la

icol_to_la(icol, unique=False, omit_nulls=False)

Get one column as a list, by position, with options.

A negative position counts from the end, so -1 is the last column. A position that is out of range raises IndexError. A Daf with no rows gives an empty list.

Parameters:

Name Type Description Default
icol int

The column position.

required
unique bool

If True, leave out repeated values and keep the order.

False
omit_nulls bool

If True, leave out the empty values.

False

Returns:

Type Description
list

The values of the column.

Raises:

Type Description
IndexError

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

Examples:

Create a small Daf of people. One age is not known:

>>> daf = Daf(cols=['id', 'city', 'age'], lol=[['p1', 'Denver', 34], ['p2', 'Austin', ''], ['p3', 'Denver', 27]], keyfield='id')
>>> daf

| id |  city  | age |
| -: | -----: | --: |
| p1 | Denver |  34 |
| p2 | Austin |     |
| p3 | Denver |  27 |

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

Read a column by position, the last one, and each value once:

>>> daf.icol_to_la(1)
['Denver', 'Austin', 'Denver']
>>> daf.icol_to_la(-1)
[34, '', 27]
>>> daf.icol_to_la(1, unique=True)
['Denver', 'Austin']
>>> daf.icol_to_la(5)
Traceback (most recent call last):
    ...
IndexError: icol: column position 5 is out of range for 3 columns.

Leave out the empty values, and the repeats:

>>> plans = Daf(cols=['id', 'plan'], lol=[['c1', 'basic'], ['c2', 'pro'], ['c3', ''], ['c4', 'basic']])
>>> plans.icol_to_la(1, omit_nulls=True)
['basic', 'pro', 'basic']
>>> plans.icol_to_la(1, unique=True, omit_nulls=True)
['basic', 'pro']

By condition

select_where

select_where(where, indirect_col=None)

Select the rows for which a function is true.

The function gets each row, as a KeyedList. Read cells by column name, as in row['n']. Values are used as stored, so convert text first if the Daf was read from a CSV.

With indirect_col, a name that is not a column is looked up in the dict held in that column.

If the test only compares columns to values, use select_by_dict(). It compares the cells by position and does not call a function for each row. For 200,000 rows by 50 columns it took 0.012 s, against 0.15 s for this method.

The new Daf shares the selected rows with this one. The keyfield and dtypes carry over.

To test a value against a list, a set or another table, write the test in the function. There is no need to build a list of bools first. Build a set of the values before the call, so that each lookup is fast and the set is built once. The function can use and, or, not and any other Python. It is called once for each row, so for a test on one column of a large Daf it is not the fastest way. For a test of equality, or of "any of these values", use select_by_dict() with a list of dicts, as in select_by_dict([{'name': n} for n in names]). It took 0.009 s where select_where() took 0.15 s, for 200,000 rows and 100 names. A comprehension over col(), followed by select_irows(), is also faster than a function.

Parameters:

Name Type Description Default
where Callable

A function that takes a row and returns True to keep it.

required
indirect_col str | None

A column that holds a dict, to read names that are not columns from.

None

Returns:

Type Description
'Daf'

The new Daf.

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=''

Select the people over 30, with a function of the row:

>>> daf.select_where(lambda row: row['age'] > 30)

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

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

Create a Daf of four people, to select by a set of cities:

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

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

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

Select the people in these cities, those not in them, and combine conditions:

>>> keep = {'Denver', 'Boston'}
>>> daf.select_where(lambda row: row['city'] in keep)

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

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

>>> daf.select_where(lambda row: row['city'] not in keep)

| id |  city  | age |
| -: | -----: | --: |
|  2 | Austin |  52 |

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

>>> daf.select_where(lambda row: row['city'] in keep and row['age'] > 30)

| id |  city  | age |
| -: | -----: | --: |
|  1 | Denver |  34 |
|  4 | Denver |  41 |

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

>>> daf.select_where(lambda row: row['id'] % 2 == 0 or row['city'] == 'Boston')

| id |  city  | age |
| -: | -----: | --: |
|  2 | Austin |  52 |
|  3 | Boston |  27 |
|  4 | Denver |  41 |

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

The values can come from another Daf. Make the set once, outside the function:

>>> other = Daf(cols=['city'], lol=[['Denver'], ['Boston']], keyfield='city')
>>> other

|  city  |
| -----: |
| Denver |
| Boston |

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

>>> other_keys = set(other.keys())
>>> daf.select_where(lambda row: row['city'] in other_keys)

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

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

For a large Daf, the faster form picks the positions from the column:

>>> daf.select_irows([irow for irow, v in enumerate(daf.col('city')) if v in keep])

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

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

For sparse data, where each row holds a dict in one column, indirect_col names that column. Then the function can read the dict's keys as if they were columns. A row that lacks a key gets NULL:

>>> customers = Daf(cols=['id', 'cart'], keyfield='id', lol=[
...     ['c1', {'apples': 1}], ['c2', {'apples': 1, 'pears': 2}], ['c3', {'pears': 1}]])
>>> customers.select_where(lambda row: row['apples'] == 1, indirect_col='cart').keys()
['c1', 'c2']

select_where_idxs

select_where_idxs(where)

Get the positions of the rows for which a function is true.

The function gets each row as a KeyedList, whatever the itermode is, as in select_where(). Read cells by column name, as in row['n']. For a test that only compares columns to values, select_by_dict() is faster.

The positions are a snapshot. Inserting, removing or sorting rows makes them point to other rows. Use them right away. To keep a reference to a row for longer, keep its key.

Parameters:

Name Type Description Default
where Callable

A function that takes a row and returns True to keep it.

required

Returns:

Type Description
T_li

The row positions.

Raises:

Type Description
KeysDisabledError

The Daf has rows and no column names.

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=''

Find the positions of the people over 30:

>>> daf.select_where_idxs(lambda row: row['age'] > 30)
[0, 1]

split_where

split_where(where, *, indirect_col=None)

Split the rows in two, by a function that is true or false for each row.

This is deprecated. Use group_where() with a function that returns True or False. It gives the two groups under the keys True and False. A side with no rows has no group, so read each side with .get().

The function gets each row, as in select_where(). Both new Daf instances share their rows with this one, so changing a cell in one changes it here too. The keyfield and dtypes carry over to both.

Parameters:

Name Type Description Default
where Callable

A function that takes a row and returns True or False.

required
indirect_col str | None

A column that holds a dict, to read names that are not columns from.

None

Returns:

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

A tuple of the Daf of the rows where the function is true and the Daf of the others.

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 the people into those over 30 and the rest:

>>> older, younger = daf.split_where(lambda row: row['age'] > 30)
>>> older

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

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

>>> younger

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

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

With indirect_col, the function can read the keys of the dict in that column as columns:

>>> customers = Daf(cols=['id', 'cart'], keyfield='id', lol=[
...     ['c1', {'apples': 1}], ['c2', {'apples': 1, 'pears': 2}], ['c3', {'pears': 1}]])
>>> with_pears, without_pears = customers.split_where(lambda row: row['pears'] != '', indirect_col='cart')
>>> with_pears.keys(), without_pears.keys()
(['c2', 'c3'], ['c1'])

select_by_dict

select_by_dict(
    selector_da, expectmax=-1, inverse=False, keyfield=""
)

Select the rows that match every field of a dict, or any one of a list of dicts.

With a dict, a row matches if each key is a column whose value in that row equals the value given. With a list of dicts, a row matches if it matches at least one of the dicts. So a dict is an AND of equalities, and a list is an OR of those. With inverse=True the rows that do not match are returned. The cells are compared by position, so no row is turned into a dict.

To select the rows whose cell is any of several values, give one small dict for each value, as in [{'name': n} for n in names]. To select by several columns together, give a dict for each combination, as in [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}]. The dicts are grouped by their keys, and the values of each group are put in a set, so a row costs about one lookup however many dicts there are. This is much faster than select_where() with a function. The result is the same as comparing with ==. A value or a cell that cannot be hashed, such as a list or a dict held in a cell, is compared with == as well. It never raises an error, and it takes a slower path for that call.

A value in a dict is only ever compared for equality. A list or a set given as a value matches a cell that holds an equal list or set, and not a cell that is one of its items. To say "any of these", use a list of dicts.

An empty list matches no row. An empty dict matches every row. A dict that names a column that is not there matches no row, and the other dicts still apply.

A Daf with rows and no column names raises KeysDisabledError. The new Daf is a live view of this one. It has its own outer row list, and its rows are the same lists as the rows of this Daf. Changing a value in it changes this Daf. Adding a column with insert_col() or insert_idx_col() does not, because those copy shared rows first. Use copy('editable') for rows of your own.

Parameters:

Name Type Description Default
selector_da T_da | T_loda

A dict of column names and the values they must have, or a list or tuple of such dicts.

required
expectmax int

If this is not -1 and more rows match, raise LookupError.

-1
inverse bool

If True, return the rows that do not match.

False
keyfield str | int | T_ta

The keyfield of the new Daf. If empty, the keyfield of this Daf.

''

Returns:

Type Description
'Daf'

The new Daf.

Raises:

Type Description
LookupError

More than expectmax rows match.

KeysDisabledError

The Daf has rows and no column names.

TypeError

selector_da is not a dict, or a list or tuple of dicts.

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=''

Select the rows whose city is Austin, and the rows whose city is not:

>>> daf.select_by_dict({'city': 'Austin'})

| id |  city  | age |
| -: | -----: | --: |
|  2 | Austin |  52 |

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

>>> daf.select_by_dict({'city': 'Austin'}, inverse=True)

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

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

Select the rows that match any of several dicts:

>>> daf.select_by_dict([{'city': 'Denver'}, {'city': 'Boston'}])

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

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

A dict with several fields matches a row that has all of them:

>>> daf.select_by_dict([{'city': 'Denver', 'age': 34}, {'city': 'Boston', 'age': 99}])

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

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

Select the rows whose city is in neither of two cities:

>>> cities = ['Denver', 'Austin']
>>> daf.select_by_dict([{'city': city} for city in cities], inverse=True)

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

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

Give the new Daf another keyfield:

>>> customers = Daf(cols=['id', 'plan', 'city'], keyfield='id', lol=[
...     ['c1', 'basic', 'Denver'], ['c2', 'pro', 'Denver'], ['c3', 'basic', 'Austin']])
>>> customers.select_by_dict({'plan': 'basic'}, keyfield='city').keys()
['Denver', 'Austin']

Check how many rows match, with expectmax. More than that raises LookupError:

>>> customers.select_by_dict({'plan': 'pro'}, expectmax=1).keys()
['c2']
>>> customers.select_by_dict({'plan': 'basic'}, expectmax=1)
Traceback (most recent call last):
...
LookupError: select_by_dict(): 2 rows match, more than expectmax=1.

select_first_row_by_dict

select_first_row_by_dict(selector_da, inverse=False)

Get the first row that matches every field of a dict.

The matching rule is that of select_by_dict(). With inverse=True it is the first row that does not match.

Parameters:

Name Type Description Default
selector_da T_da

The column names and the values they must have.

required
inverse bool

If True, find the first row that does not match.

False

Returns:

Type Description
T_ma

The row, as a dict or a KeyedList according to itermode. An empty dict if none matches.

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=''

Find the first row whose city is Austin. No match gives an empty dict:

>>> daf.select_first_row_by_dict({'city': 'Austin'})
{'id': 2, 'city': 'Austin', 'age': 52}
>>> daf.select_first_row_by_dict({'city': 'Miami'})
{}

With inverse=True, the first row that does not match:

>>> customers = Daf(cols=['id', 'plan'], lol=[['c1', 'basic'], ['c2', 'pro'], ['c3', 'basic']])
>>> customers.select_first_row_by_dict({'plan': 'basic'}, inverse=True)
{'id': 'c2', 'plan': 'pro'}

Index translation

krows_to_irows

krows_to_irows(krows, inverse=False, silent_error=False)

Turn row keys into row positions.

This is the step that lets my_daf['r2'] work. Call it when you need the positions themselves. The Daf must have a keyfield, or a key index passed in as kd.

The keys may be a key, a list of keys, or a tuple that gives an inclusive range of keys. A range is made from positions, so the keys must be in the same order as the rows.

The first lookup builds the key index, by reading the keyfield column. In one test with 200,000 rows that took 0.05 s, and a later lookup took about 2 microseconds. Adding or removing rows clears the index, and the next lookup builds it again.

Parameters:

Name Type Description Default
krows slice | str | T_la | int | Tuple[Any, Any] | T_lota | Iterable | None

A key, a list of keys, or a tuple that gives a range of keys.

required
inverse bool

If True, return the positions of the rows that are not selected.

False
silent_error bool

If True, keys that are not found are ignored.

False

Returns:

Type Description
slice | int | T_li | range

The row positions.

Raises:

Type Description
KeysDisabledError

There is no keyfield and no key index, or the keyfield is not a column.

KeyError

A key is not found and silent_error is False.

Examples:

Create a small Daf of people, keyed by id. One age is not known:

>>> daf = Daf(cols=['id', 'city', 'age'], lol=[['p1', 'Denver', 34], ['p2', 'Austin', ''], ['p3', 'Denver', 27]], keyfield='id')
>>> daf

| id |  city  | age |
| -: | -----: | --: |
| p1 | Denver |  34 |
| p2 | Austin |     |
| p3 | Denver |  27 |

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

Find the position of one key, of a list of keys, and of a range of keys:

>>> daf.krows_to_irows('p2')
[1]
>>> daf.krows_to_irows(['p3', 'p1'])
[2, 0]
>>> daf.krows_to_irows(('p1', 'p2'))
slice(0, 2, 1)
>>> daf.krows_to_irows(['p1'], inverse=True)
[1, 2]
>>> daf.krows_to_irows(['p9'], silent_error=True)
[]
>>> daf.krows_to_irows(['p9'])
Traceback (most recent call last):
    ...
KeyError: 'p9'

kcols_to_icols

kcols_to_icols(
    kcols=None, inverse=False, silent_error=False
)

Turn column names into column positions.

This is the step that lets my_daf[:, 'v'] work. A name that looks like an integer is still read as a name.

Parameters:

Name Type Description Default
kcols str | T_ls | slice | int | T_li | Tuple[Any, Any] | Iterable | None

A name, a list of names, or a tuple that gives an inclusive range of names.

None
inverse bool

If True, return the positions of the columns that are not selected.

False
silent_error bool

If True, names that are not found are ignored.

False

Returns:

Type Description
slice | int | T_li | range | None

The column positions. With no column names the result is empty, or all

slice | int | T_li | range | None

positions if inverse is True.

Raises:

Type Description
KeyError

A name is not found and silent_error is False.

Examples:

Create a small Daf of people:

>>> daf = Daf(cols=['id', 'city', 'age'], lol=[['p1', 'Denver', 34], ['p2', 'Austin', ''], ['p3', 'Denver', 27]], keyfield='id')
>>> daf

| id |  city  | age |
| -: | -----: | --: |
| p1 | Denver |  34 |
| p2 | Austin |     |
| p3 | Denver |  27 |

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

Find the position of one column, of a list of columns, and of a range of columns:

>>> daf.kcols_to_icols('city')
[1]
>>> daf.kcols_to_icols(['age', 'id'])
[2, 0]
>>> daf.kcols_to_icols(('id', 'city'))
slice(0, 2, 1)
>>> daf.kcols_to_icols('city', inverse=True)
[0, 2]
>>> daf.kcols_to_icols('email')
Traceback (most recent call last):
    ...
KeyError: 'email'

A name that is not a column raises KeyError, or is left out with silent_error=True:

>>> daf.kcols_to_icols(['city', 'email'], silent_error=True)
[1]

gkeys_to_idxs

gkeys_to_idxs(
    keydict,
    gkeys=None,
    inverse=False,
    silent_error=False,
    axis="rowkeys",
    name="unspecified",
)

Turn keys into positions, using a dict of key to position.

This is the step under krows_to_irows() and kcols_to_icols(). It is a static method. It is for internal use.

A key gives a list with one position. A list of keys gives their positions in that order. A tuple of two keys is an inclusive range, and None in it means the start or the end. A tuple of one key means that key to the end. A slice is taken as positions. With inverse, the positions that are not selected are returned.

Parameters:

Name Type Description Default
keydict Dict[str | int, int]

Maps each key to its position.

required
gkeys str | T_ls | slice | int | T_li | Tuple[Any, Any] | T_lota | Iterable | None

The keys.

None
inverse bool

If True, return the positions that are not selected.

False
silent_error bool

If True, keys that are not found are ignored.

False
axis str

The name of the index, for the error raised when it is empty.

'rowkeys'
name str

Not used.

'unspecified'

Returns:

Type Description
slice | int | T_li | range

The positions, as a list or a slice.

Raises:

Type Description
KeysDisabledError

The dict is empty, as it is for a Daf with no rows.

KeyError

A key is not found and silent_error is False.

TypeError

The keys are None, or a tuple of a length other than 1 or 2.

Examples:

Look up names in a dict of positions, as the column names of a Daf map to their places:

>>> Daf.gkeys_to_idxs({'id': 0, 'name': 1, 'age': 2}, ['age', 'id'])
[2, 0]
>>> Daf.gkeys_to_idxs({'id': 0, 'name': 1, 'age': 2}, ('id', 'name'))
slice(0, 2, 1)

With inverse=True, the positions that are not selected. With silent_error=True, a key that is not found is left out:

>>> positions = {'id': 0, 'name': 1, 'age': 2}
>>> Daf.gkeys_to_idxs(positions, ['name'], inverse=True)
[0, 2]
>>> Daf.gkeys_to_idxs(positions, ['name', 'email'], silent_error=True)
[1]

axis names the index in the error for an empty one:

>>> Daf.gkeys_to_idxs({}, ['id'], axis='rowkeys')
Traceback (most recent call last):
...
daffodil.daf.KeysDisabledError: gkeys_to_idxs(): the rowkeys index is empty, so there is nothing to look up. A Daf with no rows has no keys.