Apply, reduce, group and join¶
Functions over rows, groups and counts, and joins.
Functions over rows¶
apply ¶
apply(func, by='row', keylist=None, **kwargs)
Apply a Python function to each row, and collect the results in a new table, as Daf.apply() does.
The function gets each row as a dict, with Python NULL for a missing value, and returns what to
add to the new table, by the rules of Daf.apply():
- A dict, or a KeyedList, adds one row.
- A list of them adds a row for each, so one row can become several.
- None, an empty dict or an empty list adds nothing, so the row is left out.
The new table takes its columns from the first row returned. A later row is placed by
column name. A column it lacks gets Python NULL, and a name the first row did not have is dropped.
So have the function return every column in every row. The new table has no keyfield
and no dtypes, as the new Daf of Daf.apply() has none.
The rows are read 10,000 at a time, in order, and the results are written as they come,
all in one transaction. So a table larger than memory can be converted, and memory does
not grow. If the function raises, that error is raised, as itself, and nothing is kept.
The new table is a TEMP table, as copy() makes. Keep it with save(name).
On 300,000 rows that each became 4, this took 23.1 s, most of it in the function. A registered SQL function cannot return a row, which is why the function runs in Python.
With by='table' the function gets this SqlDaf, and its result is returned as it is.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable[..., Any]
|
The function. It takes a row and the keyword arguments, or this SqlDaf for |
required |
by
|
str
|
|
'row'
|
keylist
|
T_la | None
|
Not supported on a SqlDaf. Select the rows first. |
None
|
**kwargs
|
Any
|
Keyword arguments passed on to the function. |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
The new table, or the result of the function for |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
|
TypeError
|
The function returns something other than a dict, a KeyedList, a list of them, or nothing. |
Examples:
Create a small SqlDaf table of people, each with a list of hobbies in one cell:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_sdaf = SqlDaf('people', cols=['id', 'name', 'hobbies'], lol=[
... ['p1', 'Ana Lopez', 'chess,hiking'], ['p2', 'Ben Okafor', '']])
Make a new table with one row for each person and hobby. The function may return several rows, or none:
>>> def split_hobbies(row):
... return [{'id': row['id'], 'hobby': hobby} for hobby in row['hobbies'].split(',') if hobby]
>>> people_sdaf.apply(split_hobbies)
| id | hobby |
| -: | -----: |
| p1 | chess |
| p1 | hiking |
%% sdaf rows=2; cols=2; keyfield=''; name='daf_tmp_people_v1'
With by='table', the function gets the whole SqlDaf, and its result is returned as it is:
>>> people_sdaf.apply(lambda table: len(table), by='table')
2
reduce ¶
reduce(
func,
by="row",
cols=None,
initial_da=None,
indirect_col="",
silent_error=False,
**kwargs,
)
Combine all the rows into one result, using a function, as Daf.reduce() does.
The function is called in Python for each row, with the same arguments and the same
result as in Daf.reduce(). A sum or a count is a reduction, as with Daf.sum_da.
The rows are read 10,000 at a time, in order, so the table is never all in memory.
Memory use still depends on the result the function builds.
- With
by='row', each row is a KeyedList of its values. Unlike in a Daf, writing to it does not change the table. - With
indirect_col, orby='sparse_row', the function gets the dict held inindirect_col, JSON or PYON text decoded as in a Daf, and the result starts asinitial_daor an empty dict. A plain sum chooses its loop once, from the first 100 rows, asDaf.reduce()describes. Withcols, the result is in the order ofcols. - With
by='table', the function gets this SqlDaf andcols.
For a plain total of columns, sum() is faster: SQLite adds them, and no row comes
into Python. by='col' is not supported, since it needs each whole column in memory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable[..., Any]
|
The reduction function, such as |
required |
by
|
str
|
|
'row'
|
cols
|
T_cs | None
|
The columns included in the reduction. All columns if None. With many columns, a KeysView or a dict is faster than a list. |
None
|
initial_da
|
T_da | None
|
The result to start from, instead of zeros. |
None
|
indirect_col
|
str
|
A column that holds a dict. Its dicts are the rows, as with |
''
|
silent_error
|
bool
|
If True, a row for which the function raises is skipped. |
False
|
**kwargs
|
Any
|
Keyword arguments passed on to the function. |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
A dict for |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
NotImplementedError
|
|
Examples:
Create a small SqlDaf table of customers, with a count of visits and a cart that maps each item to how many:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> carts_sdaf = SqlDaf('carts', cols=['id', 'visits', 'cart'], lol=[
... ['c1', 4, {'apples': 3, 'pears': 2}], ['c2', 7, {'apples': 5, 'plums': 6}]])
>>> carts_sdaf
| id | visits | cart |
| -: | -----: | ------------------------: |
| c1 | 4 | {'apples': 3, 'pears': 2} |
| c2 | 7 | {'apples': 5, 'plums': 6} |
%% sdaf rows=2; cols=3; keyfield=''; name='carts'
Total the visits:
>>> carts_sdaf.reduce(Daf.sum_da, cols=['visits'])
{'id': '', 'visits': 11, 'cart': ''}
Total the items in all the carts. Each cart holds only the items bought, so it is a sparse row:
>>> carts_sdaf.reduce(Daf.sum_da, indirect_col='cart')
{'apples': 8, 'pears': 2, 'plums': 6}
Start from a total other than zero, with initial_da:
>>> carts_sdaf.reduce(Daf.sum_da, cols=['visits'], initial_da={'visits': 100})
{'id': '', 'visits': 111, 'cart': ''}
A function of your own that fails on a row stops the reduction, unless silent_error=True, which skips that row:
>>> mixed_sdaf = SqlDaf('mixed', cols=['id', 'visits'], lol=[['c1', 4], ['c2', 'unknown'], ['c3', 7]])
>>> def add_visits(row, result, cols=None):
... result['visits'] = result['visits'] + row['visits']
... return result
>>> mixed_sdaf.reduce(add_visits, cols=['visits'], silent_error=True)
{'id': '', 'visits': 11}
Groups¶
groupby ¶
groupby(
colname="", colnames=None, omit_nulls=False, cols=None
)
Group the rows by the values of a column, as Daf.groupby() does.
The result is a KeyedList of selections, one for each value, in the order first seen. It
works as a dict, as the result of Daf.groupby() does. One query finds the values. Each
group is then select_by_dict() of its value, so Python NULL is a value like any other. Nothing
is read until a group is read.
The first groupby on a column makes an index on it, in the parent table, unless an index
already starts with it. Each group is then a lookup. Without the index, reading each
group would need a full scan of the table. On 100,000 rows in 500 groups, summing every group took 2.3 s, against
14.8 s without it. The index stays with the table, and drop_cols() or rename_cols()
of the column drops it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
colname
|
str
|
The column to group by. |
''
|
colnames
|
T_ls | None
|
Several columns to group by. See |
None
|
omit_nulls
|
bool
|
If True, leave out the rows with Python NULL in the column. |
False
|
cols
|
T_ls | None
|
Not supported on a SqlDaf. It raises NotImplementedError. |
None
|
Returns:
| Type | Description |
|---|---|
KeyedList
|
A KeyedList that maps each value to a selection. |
Raises:
| Type | Description |
|---|---|
KeyError
|
The column is not a column. |
NotImplementedError
|
|
Examples:
Create a small SqlDaf table of people. One city is not known:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_sdaf = SqlDaf('people', cols=['id', 'city', 'plan'], keyfield='id', lol=[
... ['p1', 'Denver', 'basic'], ['p2', 'Austin', 'pro'], ['p3', 'Denver', 'pro'], ['p4', '', 'basic']])
Group the people by city. Each group is a selection:
>>> groups = people_sdaf.groupby('city')
>>> {city: group_sdaf.keys() for city, group_sdaf in groups.items()}
{'Denver': ['p1', 'p3'], 'Austin': ['p2'], '': ['p4']}
Group by two columns together, as tuples:
>>> list(people_sdaf.groupby(colnames=['city', 'plan']).keys())
[('Denver', 'basic'), ('Austin', 'pro'), ('Denver', 'pro'), ('', 'basic')]
Leave out the people with no city, with omit_nulls=True:
>>> list(people_sdaf.groupby('city', omit_nulls=True).keys())
['Denver', 'Austin']
groupby_cols ¶
groupby_cols(colnames, cols=None, omit_nulls=False)
Group the rows by the values of several columns, as Daf.groupby_cols() does.
Each key is a tuple of the values, even for one column. Each group is a selection, as in
groupby().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
colnames
|
T_ls
|
The columns to group by. |
required |
cols
|
T_ls | None
|
Not supported on a SqlDaf. It raises NotImplementedError. |
None
|
omit_nulls
|
bool
|
If True, leave out the rows with Python NULL in any of the columns. |
False
|
Returns:
| Type | Description |
|---|---|
KeyedList
|
A KeyedList that maps each tuple of values to a selection. |
Raises:
| Type | Description |
|---|---|
KeyError
|
A name in |
NotImplementedError
|
|
Examples:
Create a small SqlDaf table of customers. One plan is not known:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> customers_sdaf = SqlDaf('customers', cols=['id', 'city', 'plan'], keyfield='id', lol=[
... ['c1', 'Denver', 'basic'], ['c2', 'Austin', 'pro'], ['c3', 'Denver', 'basic'], ['c4', 'Denver', 'pro'], ['c5', 'Denver', '']])
Group the customers by city and plan. Each key is a tuple:
>>> groups_klist = customers_sdaf.groupby_cols(['city', 'plan'])
>>> {key: group_sdaf.keys() for key, group_sdaf in groups_klist.items()}
{('Denver', 'basic'): ['c1', 'c3'], ('Austin', 'pro'): ['c2'], ('Denver', 'pro'): ['c4'], ('Denver', ''): ['c5']}
Leave out a row with Python NULL in any of the columns, with omit_nulls=True:
>>> {key: group_sdaf.keys() for key, group_sdaf in customers_sdaf.groupby_cols(['plan'], omit_nulls=True).items()}
{('basic',): ['c1', 'c3'], ('pro',): ['c2', 'c4']}
groupby_repeated_cols ¶
groupby_repeated_cols(colnames, exclude=None)
Group the rows whose key repeats, as Daf.groupby_repeated_cols() does.
The repeated keys are found in one query, a GROUP BY that keeps the keys with more than
one row. So no group is made for a key seen once, and nothing comes into memory but the
keys. Each group is a selection of the rows with its key, in table order, as in
groupby_cols(). The groups come in the order of their first rows. An empty result means
no key repeats.
Python NULL is a value, so two rows with a blank in the same key column match. The text ''
and SQL NULL are one value. A row is left out if any column named in exclude holds one of
its values. Values compare as stored, so an int 0 does not match the text '0'.
On the 133,422 rows of a BIF table, finding the repeated keys of one or three columns took 0.09 to 0.14 s. An index on the key columns is made only when some key repeats, so each selection reads its rows by the index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
colnames
|
T_ls
|
The columns that make the key of a row. |
required |
exclude
|
Dict[str, T_la] | None
|
For each column named, the values that keep a row out of every group. |
None
|
Returns:
| Type | Description |
|---|---|
T_klosdaf
|
A KeyedList that maps each repeated key, a tuple of values, to a selection of its rows. |
Raises:
| Type | Description |
|---|---|
KeyError
|
A name in |
Examples:
Create a small SqlDaf table of sign-ups, where some people signed up more than once:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> signups_sdaf = SqlDaf('signups', cols=['id', 'name', 'birth_year', 'status'], keyfield='id', lol=[
... ['s1', 'Ana Lopez', 1990, 'ok'], ['s2', 'Ben Okafor', 1972, 'ok'], ['s3', 'Ana Lopez', 1990, 'spam'],
... ['s4', 'Chen Wu', 1997, 'ok'], ['s5', 'Ben Okafor', 1972, 'ok']])
>>> signups_sdaf
| id | name | birth_year | status |
| -: | ---------: | ---------: | -----: |
| s1 | Ana Lopez | 1990 | ok |
| s2 | Ben Okafor | 1972 | ok |
| s3 | Ana Lopez | 1990 | spam |
| s4 | Chen Wu | 1997 | ok |
| s5 | Ben Okafor | 1972 | ok |
%% sdaf rows=5; cols=4; keyfield='id'; name='signups'
Group the rows whose name and birth year repeat. A pair seen once makes no group:
>>> {key: group_sdaf.keys() for key, group_sdaf in signups_sdaf.groupby_repeated_cols(['name', 'birth_year']).items()}
{('Ana Lopez', 1990): ['s1', 's3'], ('Ben Okafor', 1972): ['s2', 's5']}
Leave out the rows marked spam first, with exclude, so that pair no longer repeats:
>>> {key: group_sdaf.keys() for key, group_sdaf in signups_sdaf.groupby_repeated_cols(['name', 'birth_year'], exclude={'status': ['spam']}).items()}
{('Ben Okafor', 1972): ['s2', 's5']}
group_where ¶
group_where(where, *, indirect_col=None, cols=None)
Group the rows by the keys a Python function returns, as Daf.group_where() does.
The function gets each row as a KeyedList, as in select_where(), and returns a key, a
list of keys, or None. A row goes into the group of each key, so a row can be in any
number of groups, and None leaves it out. As in Daf.group_where(), any iterable other
than a str is a list of keys, a tuple too. So to use a tuple as one key, return a list
of tuples.
The function runs once for each row, in one pass, and each (key, row) pair is written to a TEMP table. Each group is then a selection of the rows listed under its key, in the order of this SqlDaf. Nothing more is read until a group is read. The result is a KeyedList of selections, in the order the keys were first returned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
where
|
Callable[[Any], Any]
|
A function of a row: a key, a list of keys, or None. |
required |
indirect_col
|
str | None
|
Not supported on a SqlDaf. It raises NotImplementedError. |
None
|
Returns:
| Type | Description |
|---|---|
KeyedList
|
A KeyedList that maps each key to a selection. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
|
Examples:
Create a small SqlDaf table of people:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_sdaf = SqlDaf('people', cols=['id', 'city'], lol=[['p1', 'Denver'], ['p2', 'Austin'], ['p3', 'Denver']])
Put each person in two groups, their city and 'all'. The function returns the groups of a row:
>>> groups = people_sdaf.group_where(lambda row: [row['city'], 'all'])
>>> {key: len(group_sdaf) for key, group_sdaf in groups.items()}
{'Denver': 2, 'all': 3, 'Austin': 1}
groupby_reduce ¶
groupby_reduce(
colname,
func,
by="row",
reduce_cols=None,
diagnose=False,
batch_size=10000,
**kwargs,
)
Group the rows by one column and reduce each group to one row, as Daf.groupby_reduce() does.
Use it to turn many rows of one key into one row, such as the order lines of an order into one record of the order.
The groups are reduced inside SQLite, in one query, by a registered aggregate,
as groupby_aggregate() does. No query is made for each group.
- With
by='row', the rows of each group become a Daf of the columns the group holds. These arereduce_cols, or all columns. The cells are as stored, so a dict cell is text.Daf.reduce()reduces it, so the function is called just asDaf.groupby_reduce()calls it. A plainDaf.sum_daadds down each column there, with no call for each row. - With
by='sparse_row', the function gets the dict held in the cell ofindirect_col. Itscolsisreduce_cols, and the reduction starts as an empty dict.
For totals of columns that hold only numbers, groupsum_daf() adds them in SQL, several times faster.
The new table has a row for each value of the column, with the column as its keyfield.
With by='row' it has the columns of this table. The columns not reduced are empty.
With by='sparse_row' it has two: this column, and the column named by indirect_col.
That cell holds the dict of the group, with only the keys found in the group, as compact JSON text.
With reduce_cols and a plain sum, each dict holds the columns its group has, in the order of reduce_cols.
Results are in daffodil form, as groupby_aggregate() describes.
The new table is a TEMP table, as copy() makes. Keep it with save(name).
It differs from Daf.groupby_reduce() in three ways:
- The rows are in the sorted order of the column, not in the order first seen. SQL NULL and '' are one group, first.
- Each group is a plain Daf of the rows, with no keyfield and no dtypes.
by='table'is not supported.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
colname
|
str
|
The column to group by. |
required |
func
|
Callable[..., Any]
|
The reduction function, such as |
required |
by
|
str
|
|
'row'
|
reduce_cols
|
T_ls | None
|
The columns to reduce. All columns except |
None
|
diagnose
|
bool
|
If True, show the query and the first rows of the result. |
False
|
batch_size
|
int
|
Not used. It is kept so that existing calls work. |
10000
|
**kwargs
|
Any
|
Keyword arguments passed on to the function, and |
{}
|
Returns:
| Type | Description |
|---|---|
SqlDaf
|
A new SqlDaf with one row for each group. |
Raises:
| Type | Description |
|---|---|
KeyError
|
The column is not a column. |
NotImplementedError
|
|
Examples:
Create a small SqlDaf table of carts, each a dict of item to count, with the city of the customer:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> carts_sdaf = SqlDaf('carts', cols=['city', 'cart'], lol=[
... ['Denver', {'apples': 3}], ['Austin', {'apples': 5, 'pears': 2}], ['Denver', {'pears': 4}]])
Total the items for each city, into a new table. Each cart is a sparse row:
>>> carts_sdaf.groupby_reduce('city', Daf.sum_da, indirect_col='cart')
| city | cart |
| -----: | ---------------------: |
| Austin | {"apples":5,"pears":2} |
| Denver | {"apples":3,"pears":4} |
%% sdaf rows=2; cols=2; keyfield='city'; name='daf_tmp_carts_v1'
Reduce only some columns, with reduce_cols. The groups come in sorted order:
>>> orders_sdaf = SqlDaf('orders', cols=['id', 'city', 'qty'], lol=[['o1', 'Denver', 2], ['o2', 'Austin', 6], ['o3', 'Denver', 1]],
... dtypes={'id': str, 'city': str, 'qty': int})
>>> orders_sdaf.groupby_reduce('city', Daf.sum_da, reduce_cols=['qty'])
| id | city | qty |
| -: | -----: | --: |
| | Austin | 6 |
| | Denver | 3 |
%% sdaf rows=2; cols=3; keyfield='city'; name='daf_tmp_orders_v2'
groupby_aggregate ¶
groupby_aggregate(
groupby_cols,
func,
reduce_cols,
result_cols=None,
diagnose=False,
**kwargs,
)
Group the rows and reduce each group with a Python function, in one SQL query.
The function is registered in SQLite as an aggregate.
SQLite groups the rows and gives the function each row of a group, in the order of the table.
The function returns one result for each group.
So no rows are read into Python, except one at a time through the function.
It is the same reduction as groupby_reduce(), and faster when there are many small groups.
The function has the form of Daf.sum_da(): it takes a row as a dict and the reduction
so far, and returns the reduction.
There are two forms, by the number of columns:
- One column. The function gets the cell as the row, if it holds a dict, as text of JSON or PYON. This merges or totals concise dicts, which SQL cannot read. The result cell is the reduced dict, as compact JSON text. A cell that holds a plain value is given as a row of one column, and the result is its reduced value. An empty cell is an empty dict.
- Several columns. The function gets a dict of the grouping columns and these
columns, with each dict cell decoded. The reduction starts with 0 for each column of
reduce_cols, as inDaf.reduce(). The result has a column for each ofresult_cols.
In a result, a dict or list is compact JSON text. True and False are 1 and 0, and None is
NULLSTR, as normalize_val() gives them.
The new table has the grouping columns, then the result columns, and one row for each
group, in the sorted order of the grouping columns. SQL NULL and '' are one group, first.
With one grouping column, it is the keyfield. The table is a TEMP table, as copy() makes.
Keep it with save(name).
For totals of columns that hold only numbers, groupsum_daf() adds them in SQL, several times faster.
An error in the function is raised as itself, not as the short error SQLite reports.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
groupby_cols
|
str | T_ls
|
The column, or columns, to group by. |
required |
func
|
Callable[..., Any]
|
The reduction function, such as |
required |
reduce_cols
|
str | T_ls
|
The columns given to the function. |
required |
result_cols
|
T_ls | None
|
The columns of the result, filled from the reduction. |
None
|
diagnose
|
bool
|
If True, show the query and the first rows of the result. |
False
|
**kwargs
|
Any
|
Keyword arguments passed on to the function. |
{}
|
Returns:
| Type | Description |
|---|---|
SqlDaf
|
A new SqlDaf with one row for each group. |
Raises:
| Type | Description |
|---|---|
KeyError
|
A grouping or reduced column is not a column. |
Examples:
Create a small SqlDaf table of carts, with a count of visits and a cart of items:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> carts_sdaf = SqlDaf('carts', cols=['city', 'visits', 'cart'], lol=[
... ['Denver', 4, {'apples': 3}], ['Austin', 7, {'apples': 5, 'pears': 2}], ['Denver', 2, {'pears': 4}]])
Total the carts for each city, inside SQLite:
>>> carts_sdaf.groupby_aggregate('city', Daf.sum_da, 'cart')
| city | cart |
| -----: | ---------------------: |
| Austin | {"apples":5,"pears":2} |
| Denver | {"apples":3,"pears":4} |
%% sdaf rows=2; cols=2; keyfield='city'; name='daf_tmp_carts_v1'
Give the function two columns, and keep only the visits in the result:
>>> carts_sdaf.groupby_aggregate('city', Daf.sum_da, ['visits', 'cart'], result_cols=['visits'])
| city | visits |
| -----: | -----: |
| Austin | 7 |
| Denver | 6 |
%% sdaf rows=2; cols=2; keyfield='city'; name='daf_tmp_carts_v2'
groupsum_daf ¶
groupsum_daf(
colname, by="row", reduce_cols=None, indirect_col=""
)
Group by a column and add up the other columns of each group, as Daf.groupsum_daf() does.
One GROUP BY does it all in SQLite. The result is a Daf in memory, with one row for each
value, in the order first seen, and colname as its keyfield. As in a
Daf, only numbers are added: text, even text of digits, counts as 0, and a column with
no numbers in a group totals 0. A column not in reduce_cols is Python NULL.
Empty cells do not change the type of a total. SQL NULL and the text '' are skipped,
so a column of integers with empty cells totals as an int, as in a Daf.
A total is a float only when the group holds a float.
A plain SQL SUM() would count '' as 0 and make the total a float, which is why it is not used.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
colname
|
str
|
The column to group by. |
required |
by
|
str
|
|
'row'
|
reduce_cols
|
T_ls | None
|
The columns to add. All but |
None
|
indirect_col
|
str
|
A column that holds a dict. Each group's dicts are added into one, in that column, as JSON text. |
''
|
Returns:
| Type | Description |
|---|---|
Daf
|
A Daf in memory, with one row for each group. |
Raises:
| Type | Description |
|---|---|
KeyError
|
|
ValueError
|
|
NotImplementedError
|
|
Examples:
Create a small SqlDaf table of orders, with the city they were shipped to:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> orders_sdaf = SqlDaf('orders', cols=['city', 'qty', 'amount'], lol=[
... ['Denver', 2, 25.0], ['Austin', 6, 24.0], ['Denver', 1, 30.5]])
Total the amount for each city. A column not totaled is Python NULL:
>>> orders_sdaf.groupsum_daf('city', reduce_cols=['amount'])
| city | qty | amount |
| -----: | --: | -----: |
| Denver | | 55.5 |
| Austin | | 24.0 |
%% daf rows=2; cols=3; keyfield='city'; name=''
Total the items in the carts of each city, where each cart is a dict of item to count:
>>> carts_sdaf = SqlDaf('carts', cols=['id', 'city', 'cart'], lol=[
... ['c1', 'Denver', {'apples': 3}], ['c2', 'Denver', {'apples': 5, 'pears': 2}], ['c3', 'Austin', {'pears': 4}]])
>>> carts_sdaf.groupsum_daf('city', indirect_col='cart')
| city | cart |
| -----: | ---------------------: |
| Austin | {"pears":4} |
| Denver | {"apples":8,"pears":2} |
%% daf rows=2; cols=2; keyfield='city'; name='daf_tmp_carts_v1'
sum ¶
sum(colnames_ls=None)
Total the columns, as Daf.sum() does, and return a dict of the totals.
Numbers are totalled by SQLite. A column that also holds text has its text cells read
into Python and added as Daf.sum() adds them: text that is not a number raises
ValueError. Python NULL is skipped. Each total starts as a
float, and is converted to the dtype of its column if there is one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
colnames_ls
|
T_ls | None
|
The columns to total. All if None. Name only the columns that hold numbers. |
None
|
Returns:
| Type | Description |
|---|---|
T_da
|
A dict that maps each column name to its total. |
Raises:
| Type | Description |
|---|---|
ValueError
|
A text cell cannot be converted to a number. |
Examples:
Create a small SqlDaf table of orders:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> orders_sdaf = SqlDaf('orders', cols=['qty', 'amount'], lol=[[2, 25.0], [6, 24.0], [1, 30.5]])
Total every column:
>>> orders_sdaf.sum()
{'qty': 9.0, 'amount': 79.5}
Total only some columns. A table with a text column needs them named:
>>> named_sdaf = SqlDaf('named', cols=['id', 'qty', 'amount'], lol=[['o1', 2, 25.0], ['o2', 6, 24.0]],
... dtypes={'id': str, 'qty': int, 'amount': float})
>>> named_sdaf.sum(['qty'])
{'qty': 8}
Counts¶
valuecounts_for_colname ¶
valuecounts_for_colname(
colname, sort=False, reverse=True, omit_nulls=False
)
Count how often each value occurs in one column, as Daf.valuecounts_for_colname() does.
One GROUP BY counts them in SQLite, so no column is read into Python. The values are in
the order first seen, or by count with sort. Python NULL is counted as Python NULL, unless
omit_nulls. A column that does not exist gives an empty dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
colname
|
str
|
The column to count. |
required |
sort
|
bool
|
If True, order by count. |
False
|
reverse
|
bool
|
With |
True
|
omit_nulls
|
bool
|
If True, leave out the count of Python NULL. |
False
|
Returns:
| Type | Description |
|---|---|
Dict[Any, int]
|
A dict that maps each value to its count. |
Examples:
Create a small SqlDaf table of people. One city is not known:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_sdaf = SqlDaf('people', cols=['id', 'city'], lol=[
... ['p1', 'Denver'], ['p2', 'Austin'], ['p3', 'Denver'], ['p4', ''], ['p5', 'Denver']])
Count the people in each city, the most common first:
>>> people_sdaf.valuecounts_for_colname('city', sort=True)
{'Denver': 3, 'Austin': 1, '': 1}
Count them with the least common first:
>>> people_sdaf.valuecounts_for_colname('city', sort=True, reverse=False)
{'Austin': 1, '': 1, 'Denver': 3}
Leave out the unknown city:
>>> people_sdaf.valuecounts_for_colname('city', omit_nulls=True)
{'Denver': 3, 'Austin': 1}
valuecounts_for_colnames_ls ¶
valuecounts_for_colnames_ls(
colnames_ls=None,
sort=False,
reverse=True,
omit_nulls=False,
)
Count how often each value occurs, in each of several columns, as Daf.valuecounts_for_colnames_ls() does.
It is one GROUP BY for each column. See valuecounts_for_colname().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
colnames_ls
|
T_ls | None
|
The columns to count. All if None. |
None
|
sort
|
bool
|
If True, order each count by size. |
False
|
reverse
|
bool
|
With |
True
|
omit_nulls
|
bool
|
If True, leave out the count of Python NULL. |
False
|
Returns:
| Type | Description |
|---|---|
Dict[str, Dict[Any, int]]
|
A dict that maps each column to a dict of value and count. |
Examples:
Create a small SqlDaf table of customers, with a city and a plan. One plan is not known:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> customers_sdaf = SqlDaf('customers', cols=['id', 'city', 'plan'], lol=[
... ['c1', 'Denver', 'basic'], ['c2', 'Austin', 'pro'], ['c3', 'Denver', 'pro'], ['c4', 'Denver', 'basic'], ['c5', 'Denver', '']])
Count the values of two columns:
>>> customers_sdaf.valuecounts_for_colnames_ls(['city', 'plan'])
{'city': {'Denver': 4, 'Austin': 1}, 'plan': {'basic': 2, 'pro': 2, '': 1}}
Count them least common first, leaving out the unknown plan:
>>> customers_sdaf.valuecounts_for_colnames_ls(['city', 'plan'], sort=True, reverse=False, omit_nulls=True)
{'city': {'Austin': 1, 'Denver': 4}, 'plan': {'basic': 2, 'pro': 2}}
valuecounts_for_colname_selectedby_colname ¶
valuecounts_for_colname_selectedby_colname(
colname,
selectedby_colname,
selectedby_colvalue,
sort=False,
reverse=True,
)
Count the values of a column, in the rows where another column has a value, as Daf.valuecounts_for_colname_selectedby_colname() does.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
colname
|
str
|
The column to count. |
required |
selectedby_colname
|
str
|
The column to test. |
required |
selectedby_colvalue
|
Any
|
Only rows where that column has this value are counted. Python NULL matches Python NULL. |
required |
sort
|
bool
|
If True, order the counts by size. |
False
|
reverse
|
bool
|
With |
True
|
Returns:
| Type | Description |
|---|---|
Dict[Any, int]
|
A dict that maps each value to its count. It is empty if a column does not exist. |
Examples:
Create a small SqlDaf table of customers, with a city and a plan:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> customers_sdaf = SqlDaf('customers', cols=['id', 'city', 'plan'], lol=[
... ['c1', 'Denver', 'basic'], ['c2', 'Austin', 'pro'], ['c3', 'Denver', 'pro'], ['c4', 'Denver', 'basic'], ['c5', 'Denver', 'basic']])
>>> customers_sdaf
| id | city | plan |
| -: | -----: | ----: |
| c1 | Denver | basic |
| c2 | Austin | pro |
| c3 | Denver | pro |
| c4 | Denver | basic |
| c5 | Denver | basic |
%% sdaf rows=5; cols=3; keyfield=''; name='customers'
Count the plans of the customers in Denver only:
>>> customers_sdaf.valuecounts_for_colname_selectedby_colname('plan', 'city', 'Denver')
{'basic': 3, 'pro': 1}
Count them least common first:
>>> customers_sdaf.valuecounts_for_colname_selectedby_colname('plan', 'city', 'Denver', sort=True, reverse=False)
{'pro': 1, 'basic': 3}
valuecounts_for_colnames_ls_selectedby_colname ¶
valuecounts_for_colnames_ls_selectedby_colname(
colnames_ls=None,
selectedby_colname="",
selectedby_colvalue="",
sort=False,
reverse=True,
)
Count the values of several columns, in the rows where another column has a value, as Daf.valuecounts_for_colnames_ls_selectedby_colname() does.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
colnames_ls
|
T_ls | None
|
The columns to count. All if None. |
None
|
selectedby_colname
|
str
|
The column to test. |
''
|
selectedby_colvalue
|
Any
|
Only rows where that column has this value are counted. |
''
|
sort
|
bool
|
If True, order the counts by size. |
False
|
reverse
|
bool
|
With |
True
|
Returns:
| Type | Description |
|---|---|
Dict[str, Dict[Any, int]]
|
A dict that maps each column to a dict of value and count. |
Examples:
Create a small SqlDaf table of customers, with a city, a plan and a size of company:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> customers_sdaf = SqlDaf('customers', cols=['id', 'city', 'plan', 'size'], lol=[
... ['c1', 'Denver', 'basic', 'small'], ['c2', 'Austin', 'pro', 'large'], ['c3', 'Denver', 'pro', 'large'],
... ['c4', 'Denver', 'basic', 'small'], ['c5', 'Denver', 'basic', 'large']])
Count the plans and sizes of the customers in Denver only:
>>> customers_sdaf.valuecounts_for_colnames_ls_selectedby_colname(['plan', 'size'], 'city', 'Denver')
{'plan': {'basic': 3, 'pro': 1}, 'size': {'small': 2, 'large': 2}}
Count them least common first:
>>> customers_sdaf.valuecounts_for_colnames_ls_selectedby_colname(['plan', 'size'], 'city', 'Denver', sort=True, reverse=False)
{'plan': {'pro': 1, 'basic': 3}, 'size': {'small': 2, 'large': 2}}
valuecounts_for_colname1_groupedby_colname2 ¶
valuecounts_for_colname1_groupedby_colname2(
colname1, groupedby_colname2, sort=False, reverse=True
)
Count the values of one column, for each value of another, as the Daf method does.
One GROUP BY of the two columns counts them all. The groups, and the values in each, are in the order first seen. Use it to see whether two columns relate one to one: each group should then hold a single value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
colname1
|
str
|
The column whose values are counted. |
required |
groupedby_colname2
|
str
|
The column whose values form the groups. |
required |
sort
|
bool
|
If True, order each count by size. |
False
|
reverse
|
bool
|
With |
True
|
Returns:
| Type | Description |
|---|---|
Dict[Any, Dict[Any, int]]
|
A dict that maps each value of the second column to a dict of value and count. |
Examples:
Create a small SqlDaf table of customers, with a city and a plan:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> customers_sdaf = SqlDaf('customers', cols=['city', 'plan'], lol=[
... ['Denver', 'pro'], ['Denver', 'basic'], ['Austin', 'basic'], ['Denver', 'basic']])
Count the plans in each city:
>>> customers_sdaf.valuecounts_for_colname1_groupedby_colname2('plan', 'city')
{'Denver': {'pro': 1, 'basic': 2}, 'Austin': {'basic': 1}}
Sort each count, the most common first, or the least common first:
>>> customers_sdaf.valuecounts_for_colname1_groupedby_colname2('plan', 'city', sort=True)
{'Denver': {'basic': 2, 'pro': 1}, 'Austin': {'basic': 1}}
>>> customers_sdaf.valuecounts_for_colname1_groupedby_colname2('plan', 'city', sort=True, reverse=False)
{'Denver': {'pro': 1, 'basic': 2}, 'Austin': {'basic': 1}}
value_counts_daf ¶
value_counts_daf(
colname,
sort=False,
reverse=True,
include_total=False,
omit_nulls=False,
)
Count the values of a column into a Daf in memory, with one row per value, as Daf.value_counts_daf() does.
The counts come from valuecounts_for_colname(). The Daf has the columns colname and
counts, and a row for each value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
colname
|
str
|
The column to count. |
required |
sort
|
bool
|
If True, order by count. |
False
|
reverse
|
bool
|
With |
True
|
include_total
|
bool
|
If True, add a row with the total. |
False
|
omit_nulls
|
bool
|
If True, leave out the count of Python NULL. |
False
|
Returns:
| Type | Description |
|---|---|
Daf
|
A Daf in memory, with a row for each value. |
Examples:
Create a small SqlDaf table of customers. One plan is not known:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> customers_sdaf = SqlDaf('customers', cols=['id', 'plan'], lol=[
... ['c1', 'basic'], ['c2', 'pro'], ['c3', 'basic'], ['c4', 'team'], ['c5', 'basic'], ['c6', '']])
Count the plans into a Daf, one row for each:
>>> customers_sdaf.value_counts_daf('plan')
| plan | counts |
| ----: | -----: |
| basic | 3 |
| pro | 1 |
| team | 1 |
| | 1 |
%% daf rows=4; cols=2; keyfield=''; name=''
Sort it, leave out the unknown plan, and add a total:
>>> customers_sdaf.value_counts_daf('plan', sort=True, include_total=True, omit_nulls=True)
| plan | counts |
| --------: | -----: |
| basic | 3 |
| pro | 1 |
| team | 1 |
| **Total** | 5 |
%% daf rows=4; cols=2; keyfield=''; name=''
Sort it with the least common first:
>>> customers_sdaf.value_counts_daf('plan', sort=True, reverse=False, omit_nulls=True)
| plan | counts |
| ----: | -----: |
| pro | 1 |
| team | 1 |
| basic | 3 |
%% daf rows=3; cols=2; keyfield=''; name=''
daf_valuecount ¶
daf_valuecount(by='row', cols=None)
Count how often each value occurs, in each column, as Daf.daf_valuecount() does.
It gives the same result: a column that is not in cols gets Python NULL in place of its
counts, and a table with no rows gives an empty dict. Each column is one GROUP BY.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
by
|
str
|
Only |
'row'
|
cols
|
T_ls | None
|
The columns to count. All if None. |
None
|
Returns:
| Type | Description |
|---|---|
T_da
|
A dict that maps each column to a dict of value and count. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
|
Examples:
Create a small SqlDaf table of customers:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> customers_sdaf = SqlDaf('customers', cols=['id', 'city', 'plan'], lol=[
... ['c1', 'Denver', 'basic'], ['c2', 'Austin', 'pro'], ['c3', 'Denver', 'basic']])
Count the values of two columns. A column not counted maps to Python NULL:
>>> customers_sdaf.daf_valuecount(cols=['city', 'plan'])
{'id': '', 'city': {'Denver': 2, 'Austin': 1}, 'plan': {'basic': 2, 'pro': 1}}
Joins¶
join ¶
join(
other_daf,
how="inner",
shared_fields=None,
tag_other=False,
custom_translator_daf=None,
diagnose=False,
name="",
fill=NULL,
)
Join two SqlDaf tables on their keyfields, as Daf.join() does, in SQL.
The columns are named exactly as Daf.join() names them, by the same translator: a
column that both have gets the name of its source as a suffix, such as name_audit,
unless it is in shared_fields, and tag_other suffixes every column of the other. The
names are those of the parent tables, or daf1 and daf2 if they are the same. The rows
come as in Daf.join(): in this table's order, and for right and outer, the other
table's unmatched rows after, in its order. A cell with no match is Python NULL. The keyfield of
the result is this table's.
The keyfields must be unique, as in Daf.join(). A repeated key is not checked, and the
result is then undefined. Check the keys first if they may repeat. A Python NULL key is
undefined too: see SqlDaf.
A row found only in the other table, in a right or outer join, takes its key and its
shared fields from the other table, as in Daf.join().
Nothing runs yet. The join is resolved the first time it is read, into a TEMP table of
new rows, as Daf.join() makes new rows. A selection made from it resolves it first.
The other table may be in another database file. It is copied then into a TEMP table on this table's connection, with its key index, and the join reads the copy. Neither file changes. The copy is deleted when the join is first read, or when the join is gone unread, or when the file is closed. A chain of joins keeps each copy until the last join that uses it is read. See the Guide page on SqlDaf, Tables in other files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other_daf
|
SqlDaf
|
The SqlDaf to join with. It may be in another database file. |
required |
how
|
str
|
|
'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, except shared ones, gets a suffix. |
False
|
custom_translator_daf
|
Daf | None
|
Not supported on a SqlDaf. It raises NotImplementedError. |
None
|
diagnose
|
bool
|
Not used. |
False
|
name
|
str
|
The name of the result table. Generated if empty. |
''
|
fill
|
Any
|
The value for cells that have no match. Only Python NULL is supported. |
NULL
|
Returns:
| Type | Description |
|---|---|
SqlDaf
|
A SqlDaf of the joined rows, resolved when first read. |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
NotImplementedError
|
|
Examples:
Create two small SqlDaf tables, people and their salaries, keyed by id:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_sdaf = SqlDaf('people', cols=['id', 'name'], keyfield='id', lol=[['p1', 'Ana Lopez'], ['p2', 'Ben Okafor']])
>>> pay_sdaf = SqlDaf('pay', cols=['id', 'salary'], keyfield='id', lol=[['p1', 72000], ['p3', 58000]])
Join them, keeping every person, with a blank salary where there is none:
>>> people_sdaf.join(pay_sdaf, how='left')
| id | name | salary |
| -: | ---------: | -----: |
| p1 | Ana Lopez | 72000 |
| p2 | Ben Okafor | |
%% sdaf rows=2; cols=3; keyfield='id'; name='daf_tmp_people_join_pay_v1'
Both tables have a name column. By default, each gets its table's name as a suffix:
>>> staff_sdaf = SqlDaf('staff', cols=['id', 'name', 'salary'], keyfield='id', lol=[['p1', 'Ana Lopez', 72000]])
>>> people_sdaf.join(staff_sdaf).columns()
['id', 'name_people', 'name_staff', 'salary']
Take the name once, with shared_fields, and name the result:
>>> people_sdaf.join(staff_sdaf, shared_fields=['name'], name='people_pay')
| id | name | salary |
| -: | --------: | -----: |
| p1 | Ana Lopez | 72000 |
%% sdaf rows=1; cols=3; keyfield='id'; name='people_pay'
Give every column of the other table a suffix, with tag_other=True:
>>> people_sdaf.join(staff_sdaf, tag_other=True).columns()
['id', 'name_people', 'name_staff', 'salary_staff']
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, as Daf.join_with_residue() does.
It gives three SqlDaf objects: the inner join, as join() gives it, the rows of this table
whose key the other lacks, and the rows of the other table whose key this one lacks. Each
residue is a selection of its own table, in its own columns, as select_records() gives.
Nothing runs yet. Each result is found when it is first read. Neither table is changed.
The other table may be in another database file. The join brings it in as join() does.
Each residue reads only the keys of the other table, so a table in another file gives only
its key column there.
The rows of both tables stay as they are. Each residue looks up keys, so each table gets the
unique index on its keyfield in its own file, if it has none yet, as any lookup by key makes it.
A table opened with read_only=True allows that, since an index leaves the data as it is.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other_daf
|
SqlDaf
|
The SqlDaf to join with, by its keyfield. It may be in another database file. |
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
|
Not supported on a SqlDaf. It raises NotImplementedError. |
None
|
diagnose
|
bool
|
Not used. |
False
|
name
|
str
|
The name of the joined table. Generated if empty. |
''
|
Returns:
| Type | Description |
|---|---|
Tuple[SqlDaf, SqlDaf, SqlDaf]
|
The joined SqlDaf, the residue of this SqlDaf, and the residue of the other. |
Raises:
| Type | Description |
|---|---|
ValueError
|
A table has no keyfield. |
NotImplementedError
|
|
Examples:
Create two small SqlDaf tables, people and their salaries. Each has a key the other lacks:
>>> import tempfile
>>> SqlDaf.db_path = tempfile.mkdtemp() + '/job.db'
>>> people_sdaf = SqlDaf('people', cols=['id', 'name', 'city'], keyfield='id', lol=[
... ['p1', 'Ana Lopez', 'Denver'], ['p2', 'Ben Okafor', 'Austin'], ['p3', 'Chen Wu', 'Boston']])
>>> pay_sdaf = SqlDaf('pay', cols=['id', 'salary', 'city'], keyfield='id', lol=[
... ['p2', 64000, 'Austin'], ['p3', 58000, 'Boston'], ['p9', 81000, 'Denver']])
Join them, and keep the rows of each that have no partner:
>>> joined_sdaf, people_res_sdaf, pay_res_sdaf = people_sdaf.join_with_residue(pay_sdaf, shared_fields=['city'], name='people_pay')
>>> joined_sdaf
| id | name | city | salary |
| -: | ---------: | -----: | -----: |
| p2 | Ben Okafor | Austin | 64000 |
| p3 | Chen Wu | Boston | 58000 |
%% sdaf rows=2; cols=4; keyfield='id'; name='people_pay'
>>> people_res_sdaf.to_lod()
[{'id': 'p1', 'name': 'Ana Lopez', 'city': 'Denver'}]
>>> pay_res_sdaf.to_lod()
[{'id': 'p9', 'salary': 81000, 'city': 'Denver'}]
The other table may be in another file:
>>> pay_path = tempfile.mkdtemp() + '/pay.db'
>>> far_sdaf = pay_sdaf.copy().save('pay_far', db_path=pay_path)
>>> [result_sdaf.keys() for result_sdaf in people_sdaf.join_with_residue(far_sdaf, shared_fields=['city'])]
[['p2', 'p3'], ['p1'], ['p9']]