Skip to content

Joins and annotation

Combining two tables.

Join

join

join(
    other_daf,
    how="inner",
    shared_fields=None,
    tag_other=False,
    custom_translator_daf=None,
    diagnose=False,
    name="",
    fill=NULL,
)

Join two Daf instances on their keyfields, as in SQL.

Both need a keyfield, and it must be a single column. A composite keyfield, a tuple of columns, raises KeyError. A row of this Daf is joined with the row of other_daf that has the same key.

The join is one to one. It is not a many to many join, as in SQL. Each row of this Daf finds at most one row of the other, through its key index. If a key repeats in the other Daf, every match gets its last row. If a key repeats in this Daf, each of those rows is in the result. Check the keys first if they may repeat. See keys().

The types of join are:

inner    only the keys that are in both.
left     all keys of this Daf.
right    all keys of the other Daf.
outer    all keys of both.

Columns that only one Daf has are in the result. A column that both have is given the name of its source as a suffix, such as name_daf1, unless it is in shared_fields. The names are daf1 and daf2 if the instances have no names. For other names use custom_translator_daf, which you can start from derive_join_translator().

When a key has no match, its cells from the other side are NULL, the empty string. Pass fill=None to get None there, as earlier versions did. The keyfield of the result is the keyfield of this Daf. The result is a new Daf.

A row that only the other Daf has, in a right or outer join, comes after the rows of this Daf. It takes its key, and the columns in shared_fields, from the other Daf, since this Daf has no row for it. This holds when the keyfields have different names too. The key column of the result has the name of this Daf's keyfield.

Parameters:

Name Type Description Default
other_daf 'Daf'

The Daf to join with.

required
how str

inner, left, right or outer.

'inner'
shared_fields T_ls | None

Columns that both have and that appear only once.

None
tag_other bool

If True, every column of the other Daf, except shared ones, gets a suffix.

False
custom_translator_daf 'Daf' | None

A translator that sets all the names.

None
diagnose bool

If True, print progress messages.

False
name str

The name of the result.

''
fill Any

The value for cells that have no match.

NULL

Returns:

Type Description
'Daf'

The joined Daf.

Raises:

Type Description
ValueError

how is not one of the four.

KeysDisabledError

A Daf has no keyfield.

KeyError

A keyfield is a tuple.

Examples:

Create two small Daf tables, people and their salaries, keyed by id:

>>> 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', 'salary'], lol=[[1, 72000], [3, 58000]], keyfield='id')
>>> b_daf

| id | salary |
| -: | -----: |
|  1 |  72000 |
|  3 |  58000 |

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

Join them. By default only the keys in both are kept:

>>> a_daf.join(b_daf)

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

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

Keep every person, with NULL where there is no salary, or with another fill value:

>>> a_daf.join(b_daf, how='left')

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

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

>>> a_daf.join(b_daf, how='left', fill=None)

| id |    name    | salary |
| -: | ---------: | -----: |
|  1 |  Ana Lopez |  72000 |
|  2 | Ben Okafor |   None |

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

The tables used below. Both have item:

>>> stock = Daf(cols=['id', 'item', 'qty'], keyfield='id', lol=[['a1', 'pen', 3], ['b2', 'ink', 10], ['c3', 'pad', 7]])
>>> price = Daf(cols=['id', 'item', 'price'], keyfield='id', lol=[['a1', 'pen', 1.5], ['b2', 'ink', 4.0], ['d4', 'cap', 0.5]])

A column that both have gets a suffix for each source:

>>> stock.join(price).columns()
['id', 'item_daf1', 'qty', 'item_daf2', 'price']

shared_fields names columns that hold the same values in both, so they appear once:

>>> stock.join(price, shared_fields=['item'])

| id | item | qty | price |
| -: | ---: | --: | ----: |
| a1 |  pen |   3 |   1.5 |
| b2 |  ink |  10 |   4.0 |

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

tag_other=True gives every column of the other Daf a suffix, even one only it has:

>>> stock.join(price, tag_other=True).columns()
['id', 'item_daf1', 'qty', 'item_daf2', 'price_daf2']

Name the result:

>>> stock.join(price, how='left', shared_fields=['item'], name='stock_prices').name
'stock_prices'

For other names, edit the translator from derive_join_translator() and pass it in. Here the price column is renamed:

>>> translator = stock.derive_join_translator(price, shared_fields=['item'])
>>> translator[3, 'resolved_colname'] = 'unit_price'
>>> stock.join(price, custom_translator_daf=translator).columns()
['id', 'item', 'qty', 'unit_price']

join_with_residue

join_with_residue(
    other_daf,
    shared_fields=None,
    tag_other=False,
    custom_translator_daf=None,
    diagnose=False,
    name="",
)

Join two tables by key, and keep the rows of each that have no partner.

It gives three Daf objects:

  • the inner join: the rows whose key both tables have, with the columns of both, as join() gives them.
  • the residue of this Daf: its rows whose key the other lacks, in its own columns.
  • the residue of the other Daf: its rows whose key this Daf lacks, in its own columns.

Together they hold every row of both tables. No row is lost, and no column is added to say how a row matched. An outer join keeps every row too, but pads each unmatched row with the other table's columns, so only blank cells show it had no partner.

Use it where an unmatched row is a finding to report, not a row to drop. Neither table is changed. Each residue is a selection, which shares its rows with its table, as select_records() gives. Both tables need a keyfield.

Parameters:

Name Type Description Default
other_daf 'Daf'

The Daf to join with, by its keyfield.

required
shared_fields T_ls | None

Columns that both have and that appear only once in the join.

None
tag_other bool

If True, every column of the other, except shared ones, gets a suffix.

False
custom_translator_daf 'Daf | None'

A translator that sets the names of the joined columns. See join().

None
diagnose bool

If True, log the steps of the join.

False
name str

The name of the joined Daf.

''

Returns:

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

The joined Daf, the residue of this Daf, and the residue of the other.

Raises:

Type Description
KeysDisabledError

A table has no keyfield.

Examples:

Create two small Daf tables, people and their salaries. Each has a key the other lacks:

>>> people_daf = Daf(cols=['id', 'name', 'city'], keyfield='id', lol=[
...     ['p1', 'Ana Lopez', 'Denver'], ['p2', 'Ben Okafor', 'Austin'], ['p3', 'Chen Wu', 'Boston']])
>>> people_daf

| id |    name    |  city  |
| -: | ---------: | -----: |
| p1 |  Ana Lopez | Denver |
| p2 | Ben Okafor | Austin |
| p3 |    Chen Wu | Boston |

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

>>> pay_daf = Daf(cols=['id', 'salary', 'city'], keyfield='id', lol=[
...     ['p2', 64000, 'Austin'], ['p3', 58000, 'Boston'], ['p9', 81000, 'Denver']])
>>> pay_daf

| id | salary |  city  |
| -: | -----: | -----: |
| p2 |  64000 | Austin |
| p3 |  58000 | Boston |
| p9 |  81000 | Denver |

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

Join them, and keep the rows of each that have no partner:

>>> joined_daf, people_res_daf, pay_res_daf = people_daf.join_with_residue(pay_daf, shared_fields=['city'])
>>> joined_daf

| id |    name    |  city  | salary |
| -: | ---------: | -----: | -----: |
| p2 | Ben Okafor | Austin |  64000 |
| p3 |    Chen Wu | Boston |  58000 |

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

>>> people_res_daf.to_lod()
[{'id': 'p1', 'name': 'Ana Lopez', 'city': 'Denver'}]
>>> pay_res_daf.to_lod()
[{'id': 'p9', 'salary': 81000, 'city': 'Denver'}]

The options of the join act as in join():

>>> people_daf.join_with_residue(pay_daf, tag_other=True, name='people_pay')[0].columns()
['id', 'name', 'city_daf1', 'salary_daf2', 'city_daf2']

join_records

join_records(
    records, translator_daf, join_names_ls=None, fill=NULL
)

Combine one record from each table into one record, using a translator.

This is a static method, and the step that join() repeats. A record may be None, which gives fill for the columns of that side. A column that a record does not have also gets fill.

Parameters:

Name Type Description Default
records List[T_ma | None]

The two records, in the order of the source names.

required
translator_daf 'Daf'

The translator, as from derive_join_translator().

required
join_names_ls T_ls | None

The two source names. Needed only if the translator names more than two sources.

None
fill Any

The value for a column that has no record, or that the record lacks. NULL by default.

NULL

Returns:

Type Description
T_da

The combined record, as a dict.

Raises:

Type Description
ValueError

The translator names more than two sources and join_names_ls is not given.

Examples:

Make the translator for a join of people and pay:

>>> translator = Daf.derive_join_translator_daf('id', 'id', ['id', 'name'], ['id', 'salary'], 'people', 'pay')

Join one row of each into one row:

>>> Daf.join_records([{'id': 1, 'name': 'Ana Lopez'}, {'id': 1, 'salary': 72000}], translator)
{'id': 1, 'name': 'Ana Lopez', 'salary': 72000}

With no row from the other table, its cells are NULL, or the fill value:

>>> Daf.join_records([{'id': 1, 'name': 'Ana Lopez'}, None], translator)
{'id': 1, 'name': 'Ana Lopez', 'salary': ''}
>>> Daf.join_records([{'id': 1, 'name': 'Ana Lopez'}, None], translator, fill=0)
{'id': 1, 'name': 'Ana Lopez', 'salary': 0}

derive_join_translator

derive_join_translator(
    other_daf,
    shared_fields=None,
    omit_other_cols=None,
    tag_other=False,
)

Work out how the columns of two Daf instances are named in a join.

The translator is a Daf with a row for each column of the result. Its columns are resolved_colname, source_name, source_colname and is_keyfield. A column name that both Daf instances have is given a suffix with the name of its source, such as name_daf1, unless it is a shared field. The names of the instances are daf1 and daf2 if they have none. The keyfields are always shared.

join() calls this. Call it yourself to see the names, or to edit the translator and give it back as custom_translator_daf.

Parameters:

Name Type Description Default
other_daf 'Daf'

The Daf to join with.

required
shared_fields T_ls | None

Columns that both have and that appear only once.

None
omit_other_cols T_ls | None

Columns of the other Daf to leave out.

None
tag_other bool

If True, every column of the other Daf, except shared ones, gets a suffix.

False

Returns:

Type Description
'Daf'

The translator Daf. Its keyfield is resolved_colname.

Examples:

Create two small Daf tables of people, which both have a name column:

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

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

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

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

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

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

See the names the join would give the columns. Each name column gets its table's suffix:

>>> a_daf.derive_join_translator(b_daf).col('resolved_colname')
['id', 'name_daf1', 'name_daf2']

The tables used below. Both have item:

>>> stock = Daf(cols=['id', 'item', 'qty'], keyfield='id', lol=[['a1', 'pen', 3]])
>>> price = Daf(cols=['id', 'item', 'price'], keyfield='id', lol=[['a1', 'pen', 1.5]])

With shared_fields, the shared column comes from this Daf only:

>>> stock.derive_join_translator(price, shared_fields=['item'])

| resolved_colname | source_name | source_colname | is_keyfield |
| ---------------: | ----------: | -------------: | ----------: |
|               id |        daf1 |             id |        True |
|             item |        daf1 |           item |       False |
|              qty |        daf1 |            qty |       False |
|            price |        daf2 |          price |       False |

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

omit_other_cols leaves columns of the other Daf out:

>>> stock.derive_join_translator(price, omit_other_cols=['item']).col('resolved_colname')
['id', 'item', 'qty', 'price']

tag_other=True gives every column of the other Daf a suffix:

>>> stock.derive_join_translator(price, tag_other=True).col('resolved_colname')
['id', 'item_daf1', 'qty', 'item_daf2', 'price_daf2']

derive_join_translator_daf

derive_join_translator_daf(
    self_keyfield,
    other_keyfield,
    self_cols,
    other_cols,
    self_name="",
    other_name="",
    shared_fields=None,
    omit_other_cols=None,
    tag_other=False,
)

Work out a join translator from column names, with no Daf instances.

This is the form that does not need two Daf instances, so SQL joins can use it. See derive_join_translator() for what the translator holds.

Parameters:

Name Type Description Default
self_keyfield str

The keyfield of the first table.

required
other_keyfield str

The keyfield of the other table.

required
self_cols T_cs

The column names of the first table.

required
other_cols T_cs

The column names of the other table.

required
self_name str

The name of the first table.

''
other_name str

The name of the other table.

''
shared_fields T_cs | None

Columns that both have and that appear only once. The list is not changed.

None
omit_other_cols T_cs | None

Columns of the other table to leave out.

None
tag_other bool

If True, every column of the other table, except shared ones, gets a suffix.

False

Returns:

Type Description
'Daf'

The translator Daf. Its keyfield is resolved_colname.

Examples:

Make the translator for a join of people and pay, from their keyfields, columns and names:

>>> translator = Daf.derive_join_translator_daf('id', 'id', ['id', 'name'], ['id', 'salary'], 'people', 'pay')
>>> translator.columns()
['resolved_colname', 'source_name', 'source_colname', 'is_keyfield']
>>> translator

| resolved_colname | source_name | source_colname | is_keyfield |
| ---------------: | ----------: | -------------: | ----------: |
|               id |      people |             id |        True |
|             name |      people |           name |       False |
|           salary |         pay |         salary |       False |

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

Give every column of the other table a suffix, with tag_other=True:

>>> tagged = Daf.derive_join_translator_daf('id', 'id', ['id', 'name'], ['id', 'salary'], 'people', 'pay', tag_other=True)
>>> tagged.col('resolved_colname')
['id', 'name', 'salary_pay']

Leave a column of the other table out, with omit_other_cols:

>>> omitted = Daf.derive_join_translator_daf('id', 'id', ['id', 'name'], ['id', 'salary', 'bonus'], 'people', 'pay', omit_other_cols=['bonus'])
>>> omitted.col('resolved_colname')
['id', 'name', 'salary']

Update

update_with_history

update_with_history(new_daf, by='', key_order=None)

Merge a rerun of some records into this table, and return the records it replaced.

Use it when some records of a saved table are made again, and the table must hold the new version while the old one is kept. This Daf is the table as it is, usually read from its CSV file with no apply_dtypes(), so every cell is text. new_daf holds the rerun records, with the same columns, in any order.

A record is all the rows with one value in the by column, as groupby() gives them. Where by is the keyfield, each record is one row. A rerun record replaces the whole prior record, even when it has fewer rows.

The rerun is compared as text. A copy of it is converted with apply_dtypes() to str with from_str=False, so 3 becomes '3' and a dict becomes its text, as a CSV file holds them. So a rerun record that equals the prior one cell by cell is no change.

The keys are taken in key_order, or in this table's order, with new keys last. For each key:

  • With no rerun record, or one equal to the prior record, the prior record is kept.
  • Otherwise the rerun record goes into the result as text. The prior record goes to history. A new key, with no prior record, gets a history row with only its key.

So history is empty exactly when nothing was taken from the rerun, and the table need not be written again. A rerun with no rows changes nothing.

Neither input is changed. Both results are new Dafs with rows of their own. updated has this Daf's columns and keyfield. history has the same columns and no keyfield.

Parameters:

Name Type Description Default
new_daf 'Daf'

The rerun records. Its columns must be the same set as this Daf's.

required
by str

The column that names a record. The keyfield of this Daf if empty.

''
key_order 'T_la | Daf | None'

The keys in the order wanted, as a list, or a Daf whose keys are used. It must hold every key of both tables. This Daf's order if None.

None

Returns:

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

A tuple of two Dafs. The first is the updated table. The second is the history, the prior rows of each changed record.

Raises:

Type Description
ValueError

No by is given and this Daf has no keyfield. The columns of the two tables differ. A key of either table is not in key_order.

Examples:

Create a small Daf of order lines, several lines for some orders. The values are text, as from a CSV file:

>>> from daffodil.daf import Daf
>>> prior_daf = Daf(cols=['order_id', 'line', 'qty'],
...                 lol=[['o1', '1', '5'], ['o1', '2', '2'], ['o2', '1', '8'], ['o3', '1', '4']])
>>> prior_daf

| order_id | line | qty |
| -------: | ---: | --: |
|       o1 |    1 |   5 |
|       o1 |    2 |   2 |
|       o2 |    1 |   8 |
|       o3 |    1 |   4 |

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

The new table changes order o1, repeats o3 as it was, and adds o4:

>>> new_daf = Daf(cols=['order_id', 'line', 'qty'], lol=[['o1', 1, 6], ['o1', 2, 2], ['o3', 1, 4], ['o4', 1, 3]])

Update it, and keep the replaced rows as history:

>>> updated_daf, history_daf = prior_daf.update_with_history(new_daf, by='order_id')
>>> updated_daf

| order_id | line | qty |
| -------: | ---: | --: |
|       o1 |    1 |   6 |
|       o1 |    2 |   2 |
|       o2 |    1 |   8 |
|       o3 |    1 |   4 |
|       o4 |    1 |   3 |

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

>>> history_daf

| order_id | line | qty |
| -------: | ---: | --: |
|       o1 |    1 |   5 |
|       o1 |    2 |   2 |
|       o4 |      |     |

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

With key_order, the keys come in that order. It must hold every key of both tables:

>>> prior_daf.update_with_history(new_daf, by='order_id', key_order=['o4', 'o3', 'o2', 'o1'])[0]

| order_id | line | qty |
| -------: | ---: | --: |
|       o4 |    1 |   3 |
|       o3 |    1 |   4 |
|       o2 |    1 |   8 |
|       o1 |    1 |   6 |
|       o1 |    2 |   2 |

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

Annotate

annotate_daf

annotate_daf(other_daf, my_to_other_dict)

Copy fields from another Daf into this one, row by row, matching on the key.

Both Daf instances need a keyfield. For each row here, the row with the same key in other_daf is found, and each field of this row named in my_to_other_dict gets the value of the other field. A key that is missing in other_daf raises KeyError. A field that is not a column here is added as a new column at the right.

Parameters:

Name Type Description Default
other_daf 'Daf'

The Daf to copy from.

required
my_to_other_dict T_ds

Maps the field to set here to the field to read there.

required

Returns:

Type Description
'Daf'

This Daf, which has been changed.

Raises:

Type Description
KeyError

A keyfield is not set, or a key is not found in other_daf.

Examples:

Create a Daf of people whose city is not known yet, and a Daf that has their cities:

>>> a_daf = Daf(cols=['id', 'city'], lol=[[1, 'unknown'], [2, 'unknown']], keyfield='id')
>>> a_daf

| id |  city   |
| -: | ------: |
|  1 | unknown |
|  2 | unknown |

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

>>> o_daf = Daf(cols=['id', 'home_city'], lol=[[1, 'Denver'], [2, 'Austin']], keyfield='id')
>>> o_daf

| id | home_city |
| -: | --------: |
|  1 |    Denver |
|  2 |    Austin |

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

Fill in each city from the other Daf, matched by key:

>>> a_daf.annotate_daf(o_daf, {'city': 'home_city'})

| id |  city  |
| -: | -----: |
|  1 | Denver |
|  2 | Austin |

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