Statistics and reporting¶
Value counts, statistics, and Markdown output.
Value counts¶
valuecounts_for_colname ¶
valuecounts_for_colname(
colname, sort=False, reverse=True, omit_nulls=False
)
Count how often each value occurs in one column.
With sort=True the dict is ordered from the most common value to the least.
Use reverse=False for the other way. A column that does not exist gives an
empty dict. An empty cell is counted as the empty string, unless
omit_nulls is True.
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 empty cells. |
False
|
Returns:
| Type | Description |
|---|---|
Dict[Any, int]
|
A dict that maps each value to its count. |
Examples:
Create a small Daf of customers, with their city and plan. One plan is not known:
>>> daf = Daf(cols=['city', 'plan'], lol=[
... ['Denver', 'pro'], ['Denver', 'basic'], ['Austin', 'basic'], ['Austin', ''],
... ['Denver', 'basic'], ['Austin', 'pro'], ['Austin', 'pro'], ['Denver', 'basic']])
>>> daf
| city | plan |
| -----: | ----: |
| Denver | pro |
| Denver | basic |
| Austin | basic |
| Austin | |
| Denver | basic |
| Austin | pro |
| Austin | pro |
| Denver | basic |
%% daf rows=8; cols=2; keyfield=''; name=''
The values come in the order first seen. The empty cell is counted as '':
>>> daf.valuecounts_for_colname('plan')
{'pro': 3, 'basic': 4, '': 1}
With sort=True, the most common value comes first. With reverse=False as well, the least
common does:
>>> daf.valuecounts_for_colname('plan', sort=True)
{'basic': 4, 'pro': 3, '': 1}
>>> daf.valuecounts_for_colname('plan', sort=True, reverse=False)
{'': 1, 'pro': 3, 'basic': 4}
Leave out the empty cells:
>>> daf.valuecounts_for_colname('plan', omit_nulls=True)
{'pro': 3, 'basic': 4}
A column that does not exist gives an empty dict, with no error:
>>> daf.valuecounts_for_colname('color')
{}
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.
The result maps each column to a dict of value and count, as valuecounts_for_colname()
gives for one column. A name that is not a column maps to an empty dict, with no error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
colnames_ls
|
T_cs | 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 empty cells. |
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 Daf of customers, with their city and plan. One plan is not known:
>>> daf = Daf(cols=['city', 'plan'], lol=[
... ['Denver', 'pro'], ['Denver', 'basic'], ['Austin', 'basic'], ['Austin', ''],
... ['Denver', 'basic'], ['Austin', 'pro'], ['Austin', 'pro'], ['Denver', 'basic']])
Every column, with no list given:
>>> daf.valuecounts_for_colnames_ls()
{'city': {'Denver': 4, 'Austin': 4}, 'plan': {'pro': 3, 'basic': 4, '': 1}}
Some columns, each sorted with the most common first, and without the empty cells:
>>> daf.valuecounts_for_colnames_ls(['plan'], sort=True, omit_nulls=True)
{'plan': {'basic': 4, 'pro': 3}}
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.
It answers a question such as how often each color occurs in group x, with no selection made
first. A name that is not a column gives an empty dict, with no error. For the counts of every
group at once, use valuecounts_for_colname1_groupedby_colname2().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
colname
|
str
|
The column to count. |
required |
selectedby_colname
|
str
|
The column to test. |
required |
selectedby_colvalue
|
str
|
Only rows where that column equals this are counted. |
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 Daf of customers, with their city and plan. One plan is not known:
>>> daf = Daf(cols=['city', 'plan'], lol=[
... ['Denver', 'pro'], ['Denver', 'basic'], ['Austin', 'basic'], ['Austin', ''],
... ['Denver', 'basic'], ['Austin', 'pro'], ['Austin', 'pro'], ['Denver', 'basic']])
Count the plans in Denver only:
>>> daf.valuecounts_for_colname_selectedby_colname('plan', 'city', 'Denver')
{'pro': 1, 'basic': 3}
The same, sorted with the most common first:
>>> daf.valuecounts_for_colname_selectedby_colname('plan', 'city', 'Denver', sort=True)
{'basic': 3, 'pro': 1}
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.
It is valuecounts_for_colname_selectedby_colname() for several columns at once. Use it for a
profile of one group, such as the plans and company sizes of the customers in one city.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
colnames_ls
|
T_cs | None
|
The columns to count. All if None. |
None
|
selectedby_colname
|
str
|
The column to test. |
''
|
selectedby_colvalue
|
str
|
Only rows where that column equals this 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 Daf of customers, with their city, plan and size of company:
>>> daf = Daf(cols=['city', 'plan', 'size'], lol=[
... ['Denver', 'pro', 'small'], ['Denver', 'basic', 'large'], ['Austin', 'basic', 'small'], ['Austin', '', 'small'],
... ['Denver', 'basic', 'large'], ['Austin', 'pro', 'large'], ['Austin', 'pro', 'large'], ['Denver', 'basic', 'large']])
Count two columns, in Austin only:
>>> daf.valuecounts_for_colnames_ls_selectedby_colname(['plan', 'size'], 'city', 'Austin')
{'plan': {'basic': 1, '': 1, 'pro': 2}, 'size': {'small': 2, 'large': 2}}
With each count sorted, the most common first:
>>> daf.valuecounts_for_colnames_ls_selectedby_colname(['plan', 'size'], 'city', 'Austin', sort=True)
{'plan': {'pro': 2, 'basic': 1, '': 1}, '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.
The data is read once. 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 Daf of customers, with their city and plan. One plan is not known:
>>> daf = Daf(cols=['city', 'plan'], lol=[
... ['Denver', 'pro'], ['Denver', 'basic'], ['Austin', 'basic'], ['Austin', ''],
... ['Denver', 'basic'], ['Austin', 'pro'], ['Austin', 'pro'], ['Denver', 'basic']])
The plans counted in each city:
>>> daf.valuecounts_for_colname1_groupedby_colname2('plan', 'city')
{'Denver': {'pro': 1, 'basic': 3}, 'Austin': {'basic': 1, '': 1, 'pro': 2}}
The same, with each count sorted, the most common first:
>>> daf.valuecounts_for_colname1_groupedby_colname2('plan', 'city', sort=True)
{'Denver': {'basic': 3, 'pro': 1}, 'Austin': {'pro': 2, 'basic': 1, '': 1}}
To check that one column depends on another, count it by the other. Here each zip code belongs to one city, so each city shows one zip code:
>>> zips_daf = Daf(cols=['city', 'zip'], lol=[['Denver', '80202'], ['Austin', '73301'], ['Denver', '80202']])
>>> zips_daf.valuecounts_for_colname1_groupedby_colname2('zip', 'city')
{'Denver': {'80202': 2}, 'Austin': {'73301': 1}}
value_counts_daf ¶
value_counts_daf(
colname,
sort=False,
reverse=True,
include_total=False,
omit_nulls=False,
)
Make a Daf that lists each value of a column and its count.
The columns are the name of the column, and counts. There is no keyfield.
With include_total a last row holds the total.
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 empty cells. |
False
|
Returns:
| Type | Description |
|---|---|
'Daf'
|
The new Daf. |
Examples:
Create a small Daf of customers, with their city and plan. One plan is not known:
>>> daf = Daf(cols=['city', 'plan'], lol=[
... ['Denver', 'pro'], ['Denver', 'basic'], ['Austin', 'basic'], ['Austin', ''],
... ['Denver', 'basic'], ['Austin', 'pro'], ['Austin', 'pro'], ['Denver', 'basic']])
Each value and its count, in the order first seen:
>>> daf.value_counts_daf('plan')
| plan | counts |
| ----: | -----: |
| pro | 3 |
| basic | 4 |
| | 1 |
%% daf rows=3; cols=2; keyfield=''; name=''
Sorted with the most common first, without the empty cells, and with a total. The total's
label is **Total**, which shows in bold in Markdown:
>>> daf.value_counts_daf('plan', sort=True, omit_nulls=True, include_total=True)
| plan | counts |
| --------: | -----: |
| basic | 4 |
| pro | 3 |
| **Total** | 7 |
%% daf rows=3; cols=2; keyfield=''; name=''
With reverse=False, the least common comes first:
>>> daf.value_counts_daf('plan', sort=True, reverse=False)
| plan | counts |
| ----: | -----: |
| | 1 |
| pro | 3 |
| basic | 4 |
%% daf rows=3; cols=2; keyfield=''; name=''
daf_valuecount ¶
daf_valuecount(by='row', cols=None)
Count how often each value occurs, in each column, using reduce() and count_values_kl().
The result maps each column to a dict of value and count. With cols, only those columns are
counted, and every other column maps to Python NULL. For a result that holds only the columns
asked for, use valuecounts_for_colnames_ls().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
by
|
str
|
How the function is applied. See |
'row'
|
cols
|
T_cs | None
|
The columns to count. All if None. |
None
|
Returns:
| Type | Description |
|---|---|
T_ma
|
A dict that maps each column to a dict of value and count. A column that is |
T_ma
|
not in |
Examples:
Create a small Daf of customers, with their city and plan. One plan is not known:
>>> daf = Daf(cols=['city', 'plan'], lol=[
... ['Denver', 'pro'], ['Denver', 'basic'], ['Austin', 'basic'], ['Austin', ''],
... ['Denver', 'basic'], ['Austin', 'pro'], ['Austin', 'pro'], ['Denver', 'basic']])
Every column:
>>> daf.daf_valuecount()
{'city': {'Denver': 4, 'Austin': 4}, 'plan': {'pro': 3, 'basic': 4, '': 1}}
One column. The others are in the result, with NULL, the empty string:
>>> daf.daf_valuecount(cols=['plan'])
{'city': '', 'plan': {'pro': 3, 'basic': 4, '': 1}}
Statistics¶
gen_stats_daf ¶
gen_stats_daf(col_def_lot)
Work out statistics for columns, given a profile for each.
col_def_lot has a tuple for each column of interest. The tuple is the column
name, a type, a format, and a profile. The profile is one of index,
attrib, file_paths, scalar or localidx, and chooses what is measured.
An index looks for repeats, an attribute counts the values, and a scalar gives
the minimum, maximum, mean and standard deviation. The type and format are not
used.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
col_def_lot
|
T_lota
|
A list of tuples of column name, type, format and profile. |
required |
Returns:
| Type | Description |
|---|---|
T_doda
|
A dict that maps each column name to its statistics, as a dict. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
A profile is not one of the five. |
Examples:
Create a small Daf of orders, with their city and quantity. One order number repeats:
>>> daf = Daf(cols=['order', 'city', 'qty'], lol=[['o1', 'Denver', 3], ['o2', 'Denver', 5], ['o2', 'Austin', 10]])
Each profile measures something else. The result is a dict for each column, with many entries. These examples pick out the main ones.
An index column should not repeat. num_within_reps counts the repeats.
within_reps_loti lists each repeat as (0, row), where row is its position. The first
time a value appears is not listed. Here o2 at row 2 repeats o2 at row 1:
>>> stats = daf.gen_stats_daf([('order', str, '', 'index')])['order']
>>> stats['num_uniques'], stats['num_within_reps'], stats['within_reps_loti']
(2, 1, [(0, 2)])
An attrib column is counted by value:
>>> daf.gen_stats_daf([('city', str, '', 'attrib')])['city']['val_counts']
{'Denver': 2, 'Austin': 1}
A scalar column gives its range, mean and standard deviation:
>>> stats = daf.gen_stats_daf([('qty', int, '', 'scalar')])['qty']
>>> stats['min'], stats['max'], stats['mean'], round(stats['stdev'], 2)
(3, 10, 6, 3.61)
A localidx column holds whole numbers, and says whether they run in sequence:
>>> stats = daf.gen_stats_daf([('qty', int, '', 'localidx')])['qty']
>>> stats['all_ints'], stats['sequential']
(True, False)
Several columns at once, each with its own profile:
>>> sorted(daf.gen_stats_daf([('city', str, '', 'attrib'), ('qty', int, '', 'scalar')]))
['city', 'qty']
Markdown and text¶
to_md ¶
to_md(
max_rows=0,
max_cols=0,
just="",
shorten_text=True,
max_text_len=80,
smart_fmt=False,
include_summary=False,
disp_cols=None,
header=None,
col_fmt=None,
show=None,
)
Make a Markdown table of the Daf, as text.
Use it to put a table into a report or a log, as in daf[0:50].to_md(). It writes every row
and column, with no summary line, unless asked. That is the difference from str(), which
is what print(daf) and an f-string give: str() keeps 10 rows and 10 columns and adds the
summary line. A SqlDaf gives the same text, and reads only the rows it shows.
The parameters shape the table:
max_rowsandmax_colskeep the first and last rows and columns, and put...in place of the middle. 0 means no limit.justsets the justification of each column, one character for each:<left,^center,>right. The default is right for every column.- Text longer than
max_text_lenloses its middle, marked.., so both ends show.shorten_text=Falsewrites it in full. smart_fmt=Trueshows numbers for people to read. A whole number gets commas, as 12,345. A float above 100 is rounded to a whole number. Above 1 it keeps one decimal, above 0.1 two, above 0.01 three, and above 0.001 four. A trailing zero is dropped, so 0.50 shows as 0.5. Only the text is changed, not the Daf.col_fmtformats the cells of the columns it names, for display only. The Daf is not changed. Each value is a Python format spec, the part after the colon in an f-string, such as'.1%'or',.2f'.'smart'gives thesmart_fmtform for that column.'smart%'gives it as a percent, so a small share such as 0.0001 shows as 0.01% and not as 0%. A function gets the cell and returns what to show. A missing value stays blank. A value the spec cannot format, such as text in a column of numbers, is shown as it is.smart_fmtdoes not change the columns thatcol_fmtnames.showshows what a plain table hides, the types. It takes one word or a list of them:'dtypes'adds each column's dtype to its header, after a colon, asage: int. The cells shown are checked. If they hold another type, it follows in parentheses, asage: int (str)for a column thatapply_dtypes()has not yet converted. A bool or a float column may hold ints. A column with no dtype keeps its name alone.from_md()reads the dtypes back.'quotes'shows each text cell as Python writes it, in quotes. Then the text'34'differs from the number 34, the empty string from None, and the text of a dict from a dict. With the summary line,from_md()takes the quotes off again.'types'shows each cell's type name in place of its value, asstrordict. A missing value stays blank. The table cannot be read back.
include_summary=Trueadds the summary line thatstr()shows, starting with%%. With it,from_md()can read the table back, as text.disp_colsnames the columns differently in the header. A dict renames the columns it names, and the others keep their names. A list names every column. The Daf keeps its own names.headerreplaces the header row as it is shown, so it must match the columns shown. Withmax_cols, usedisp_cols, which stays matched to the columns it names.
A Daf with no column names gets A, B and so on in the header, as a spreadsheet does. A
ragged Daf, with rows of different lengths, is shown with blank cells in its short rows, and
the Daf is not changed. Then the summary line ends with ragged rows detected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_rows
|
int
|
The most rows to show, the first and the last. 0 for all. |
0
|
max_cols
|
int
|
The most columns to show, the first and the last. 0 for all. |
0
|
just
|
str
|
The justification of each column, one of |
''
|
shorten_text
|
bool
|
If True, shorten text that is longer than |
True
|
max_text_len
|
int
|
The longest text to show in full. |
80
|
smart_fmt
|
bool
|
If True, show floats with fewer digits. |
False
|
include_summary
|
bool
|
If True, add a line with the size, keyfield and name. |
False
|
disp_cols
|
T_cs | None
|
Names to show in the header: a dict of column name to name shown, for some columns, or a list for every column. |
None
|
header
|
T_cs | None
|
A header row to show in place of the one made from the column names. |
None
|
col_fmt
|
T_da | None
|
How to show the cells of some columns: a dict of column name to a format spec, 'smart', 'smart%' or a function. |
None
|
show
|
str | T_ls | None
|
What else to show: 'dtypes', 'quotes' or 'types', or a list of them. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The Markdown text, ending with a newline. |
Raises:
| Type | Description |
|---|---|
KeyError
|
A name in |
ValueError
|
A word in |
Examples:
Create a small Daf of items for sale, with a price and a note. Some notes are long:
>>> daf = Daf(cols=['id', 'item', 'price', 'note'], keyfield='id', lol=[
... ['a1', 'pen', 1.5, 'blue, fine tip'],
... ['b2', 'ink', 4.0, ''],
... ['c3', 'pad', 2.25, 'lined, 80 sheets of recycled paper'],
... ['d4', 'cap', 0.333333, 'red'],
... ['e5', 'tag', 10.0, 'paper']])
Make a Markdown table of every row and column:
>>> print(daf.to_md())
| id | item | price | note |
| -: | ---: | -------: | ---------------------------------: |
| a1 | pen | 1.5 | blue, fine tip |
| b2 | ink | 4.0 | |
| c3 | pad | 2.25 | lined, 80 sheets of recycled paper |
| d4 | cap | 0.333333 | red |
| e5 | tag | 10.0 | paper |
Keep the first and last 2 rows, and the first and last column:
>>> print(daf.to_md(max_rows=4, max_cols=2))
| id | ... | note |
| --: | --: | -------------: |
| a1 | ... | blue, fine tip |
| b2 | ... | |
| ... | ... | ... |
| d4 | ... | red |
| e5 | ... | paper |
Justify the columns left, center, right and right:
>>> print(daf[0:2].to_md(just='<^>>'))
| id | item | price | note |
| :- | :--: | ----: | -------------: |
| a1 | pen | 1.5 | blue, fine tip |
| b2 | ink | 4.0 | |
Shorten long text to 20 characters, or write it in full:
>>> print(daf[:, ['id', 'note']].to_md(max_text_len=20))
| id | note |
| -: | -------------------: |
| a1 | blue, fine tip |
| b2 | |
| c3 | lined, 80..led paper |
| d4 | red |
| e5 | paper |
>>> print(daf[:, ['id', 'note']].to_md(max_text_len=20, shorten_text=False))
| id | note |
| -: | ---------------------------------: |
| a1 | blue, fine tip |
| b2 | |
| c3 | lined, 80 sheets of recycled paper |
| d4 | red |
| e5 | paper |
Show numbers for people to read. The number of decimals depends on the size:
>>> sizes = Daf(cols=['n'], lol=[[12345], [1234.56], [2.25], [0.333333], [0.0456]])
>>> print(sizes.to_md(smart_fmt=True))
| n |
| -----: |
| 12,345 |
| 1,235 |
| 2.2 |
| 0.33 |
| 0.046 |
Add the summary line:
>>> print(daf[0:2].to_md(include_summary=True))
| id | item | price | note |
| -: | ---: | ----: | -------------: |
| a1 | pen | 1.5 | blue, fine tip |
| b2 | ink | 4.0 | |
%% daf rows=2; cols=4; keyfield='id'; name=''
Show other names in the header. disp_cols stays matched to its columns when some are
hidden. header is the header row as shown, so with max_cols it would need ... too:
>>> print(daf[0:2].to_md(disp_cols=['ID', 'Item', 'Price', 'Note']))
| ID | Item | Price | Note |
| -: | ---: | ----: | -------------: |
| a1 | pen | 1.5 | blue, fine tip |
| b2 | ink | 4.0 | |
A dict renames only the columns it names:
>>> print(daf[0:2].to_md(disp_cols={'item': 'Item'}))
| id | Item | price | note |
| -: | ---: | ----: | -------------: |
| a1 | pen | 1.5 | blue, fine tip |
| b2 | ink | 4.0 | |
>>> print(daf[0:2].to_md(disp_cols=['ID', 'Item', 'Price', 'Note'], max_cols=2))
| ID | ... | Note |
| -: | --: | -------------: |
| a1 | ... | blue, fine tip |
| b2 | ... | |
>>> print(daf[0:2].to_md(header=['ID', '...', 'Note'], max_cols=2))
| ID | ... | Note |
| -: | --: | -------------: |
| a1 | ... | blue, fine tip |
| b2 | ... | |
Create a small Daf of sales by city, with a share of the total and a change from last year. One sale is not known, and one change is missing:
>>> sales = Daf(cols=['city', 'share', 'amount', 'change'], lol=[
... ['Denver', 0.3412, 12345.5, 0.0001], ['Austin', 0.6588, 'n/a', ''], ['Reno', 0.0, 9876.25, 0.25]])
>>> sales
| city | share | amount | change |
| -----: | -----: | ------: | -----: |
| Denver | 0.3412 | 12345.5 | 0.0001 |
| Austin | 0.6588 | n/a | |
| Reno | 0.0 | 9876.25 | 0.25 |
%% daf rows=3; cols=4; keyfield=''; name=''
Show some columns in a format of their own. The tiny change still shows with 'smart%'.
The missing change stays blank, and text that does not fit the format is shown as it is:
>>> print(sales.to_md(col_fmt={'share': '.1%', 'amount': ',.2f', 'change': 'smart%'}))
| city | share | amount | change |
| -----: | ----: | --------: | -----: |
| Denver | 34.1% | 12,345.50 | 0.01% |
| Austin | 65.9% | n/a | |
| Reno | 0.0% | 9,876.25 | 25% |
Give a function for a format that a spec cannot give. The other columns still get smart_fmt:
>>> print(sales.to_md(col_fmt={'amount': lambda val: f'${val:,.0f}' if isinstance(val, float) else val}, smart_fmt=True))
| city | share | amount | change |
| -----: | ----: | ------: | -----: |
| Denver | 0.34 | $12,346 | 0.0001 |
| Austin | 0.66 | n/a | |
| Reno | 0 | $9,876 | 0.25 |
Create a small Daf read from text, so every cell is text. The dtypes say what the columns should hold:
>>> people = Daf.from_csv_buff("id,age,prefs\np1,34,{'news': 1}\np2,,{}\n")
>>> people.dtypes = {'id': str, 'age': int, 'prefs': dict}
>>> people
| id | age | prefs |
| -: | --: | ----------: |
| p1 | 34 | {'news': 1} |
| p2 | | {} |
%% daf rows=2; cols=3; keyfield=''; name=''
Show the dtypes in the header. Each column that still holds text says so:
>>> print(people.to_md(show='dtypes'))
| id: str | age: int (str) | prefs: dict (str) |
| ------: | -------------: | ----------------: |
| p1 | 34 | {'news': 1} |
| p2 | | {} |
Convert the columns, and the notes are gone:
>>> print(people.apply_dtypes().to_md(show='dtypes'))
| id: str | age: int | prefs: dict |
| ------: | -------: | ----------: |
| p1 | 34 | {'news': 1} |
| p2 | | {} |
Quote the text cells. The id is text, the age is a number, and the prefs are dicts. The empty
string shows as '':
>>> print(people.to_md(show='quotes'))
| id | age | prefs |
| ---: | --: | ----------: |
| 'p1' | 34 | {'news': 1} |
| 'p2' | '' | {} |
Show each cell's type name in place of its value. A missing value stays blank:
>>> mixed = Daf(cols=['id', 'age', 'prefs'], lol=[['p1', '34', "{'news': 1}"], ['p2', 52, {'news': 0}], ['p3', '', None]])
>>> print(mixed.to_md(show='types'))
| id | age | prefs |
| --: | --: | ----: |
| str | str | str |
| str | int | dict |
| str | | None |
to_md_cols ¶
to_md_cols(
max_rows=0,
max_cols=0,
just="",
shorten_text=True,
max_text_len=80,
smart_fmt=False,
include_summary=False,
disp_cols=None,
)
Make a Markdown table in which each row of the Daf is a column.
There is no header row and no separator row. The first column holds the column names of the Daf. Use it for a Daf with few rows and many columns. Some Markdown renderers, such as Python-Markdown, show this text as plain text, because they need a header and a separator row to make a table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_rows
|
int
|
The most rows to show. 0 for all. |
0
|
max_cols
|
int
|
The most columns to show. 0 for all. |
0
|
just
|
str
|
The justification of each column. |
''
|
shorten_text
|
bool
|
If True, shorten text that is longer than |
True
|
max_text_len
|
int
|
The longest text to show in full. |
80
|
smart_fmt
|
bool
|
If True, show numbers with fewer decimal places. |
False
|
include_summary
|
bool
|
Not used. |
False
|
disp_cols
|
T_cs | None
|
Names to show in the header: a dict of column name to name shown, for some columns, or a list for every column. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The Markdown text. |
Examples:
Create a small Daf of items for sale, with a price and a note:
>>> daf = Daf(cols=['id', 'item', 'price', 'note'], lol=[
... ['a1', 'pen', 1.5, 'blue, fine tip'],
... ['b2', 'ink', 4.0, ''],
... ['c3', 'pad', 2.25, 'lined, 80 sheets of recycled paper']])
Each row of the Daf becomes a column. The first column holds the column names. The cells are centered:
>>> print(daf.to_md_cols())
| id | a1 | b2 | c3 |
| item | pen | ink | pad |
| price | 1.5 | 4.0 | 2.25 |
| note | blue, fine tip | | lined, 80 sheets of recycled paper |
max_rows limits the rows of the Daf, which are the columns here, and max_cols the columns
of the Daf, which are the lines. The middle ones become ...:
>>> print(daf.to_md_cols(max_rows=2, max_cols=2))
| id | a1 | ... | c3 |
| ... | ... | ... | ... |
| note | blue, fine tip | ... | lined, 80 sheets of recycled paper |
just has one character for each column of the text: the names, then one for each row. Here
text is shortened to 12 characters, a float is shown with fewer digits, and the names are
replaced:
>>> print(daf.to_md_cols(just='<<<<', max_text_len=12, smart_fmt=True, disp_cols=['ID', 'Item', 'Price', 'Note']))
| ID | a1 | b2 | c3 |
| Item | pen | ink | pad |
| Price | 1.5 | 4 | 2.2 |
| Note | blue,..e tip | | lined..paper |
shorten_text=False writes long text in full, whatever max_text_len is:
>>> notes = Daf(cols=['n'], lol=[['a very long note text']])
>>> print(notes.to_md_cols(max_text_len=10, shorten_text=False))
| n | a very long note text |
md_daf_table_snippet ¶
md_daf_table_snippet()
Make a short Markdown table of the Daf, with a summary line.
This is what str() shows. It keeps at most md_max_rows rows and
md_max_cols columns, 10 by default. Longer text is shortened to 80
characters.
If the Daf has no rows, it is empty, and it shows no header. The summary line says
rows=0; cols=0, because the number of columns is counted from the rows.
columns() still gives the names.
Returns:
| Type | Description |
|---|---|
str
|
The Markdown text. |
Examples:
Create a small Daf of people, and show it as a short Markdown table with its summary line:
>>> daf = Daf(cols=['id', 'name', 'age'], lol=[['p1', 'Ana Lopez', 34], ['p2', 'Ben Okafor', 52]])
>>> print(daf.md_daf_table_snippet(), end='')
| id | name | age |
| -: | ---------: | --: |
| p1 | Ana Lopez | 34 |
| p2 | Ben Okafor | 52 |
%% daf rows=2; cols=3; keyfield=''; name=''
An empty Daf has no rows and no columns, so only the summary line shows. This is so even if it has column names:
>>> Daf(cols=['id', 'name', 'age'])
%% daf rows=0; cols=0; keyfield=''; name=''
daf_to_lol_summary ¶
daf_to_lol_summary(
max_rows=10, max_cols=10, disp_cols=None
)
Make a list of lists for display, with the column names first.
If there are more rows or columns than the limits, the first and last are
kept and the middle is replaced by .... The limit is the number of data rows
kept, and an odd limit keeps the extra row at the start. A limit of 0 means no
limit, so with only max_cols all the rows are kept. The rows are not copied.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_rows
|
int
|
The most rows to keep. 0 for no limit. |
10
|
max_cols
|
int
|
The most columns to keep. 0 for no limit. |
10
|
disp_cols
|
T_cs | None
|
Names to show in the header: a dict of column name to name shown, for some columns, or a list for every column. |
None
|
Returns:
| Type | Description |
|---|---|
T_lola
|
The rows, with a header row first if there are column names. |
Examples:
Create a small Daf of items in stock:
>>> daf = Daf(cols=['id', 'item', 'qty'], lol=[['a1', 'pen', 3], ['b2', 'ink', 10], ['c3', 'pad', 7]])
The column names come first, then the rows:
>>> daf.daf_to_lol_summary()
[['id', 'item', 'qty'], ['a1', 'pen', 3], ['b2', 'ink', 10], ['c3', 'pad', 7]]
Keep 2 rows, the first and the last, with ... between them:
>>> daf.daf_to_lol_summary(max_rows=2)
[['id', 'item', 'qty'], ['a1', 'pen', 3], ['...', '...', '...'], ['c3', 'pad', 7]]
Keep 2 columns, the first and the last. The limits default to 10, and max_rows=0 means no
limit, so every row is kept:
>>> daf.daf_to_lol_summary(max_rows=0, max_cols=2)
[['id', '...', 'qty'], ['a1', '...', 3], ['b2', '...', 10], ['c3', '...', 7]]
Other names for the columns:
>>> daf.daf_to_lol_summary(disp_cols=['ID', 'Item', 'Qty'])
[['ID', 'Item', 'Qty'], ['a1', 'pen', 3], ['b2', 'ink', 10], ['c3', 'pad', 7]]
>>> daf.daf_to_lol_summary(disp_cols={'qty': 'Qty'})
[['id', 'item', 'Qty'], ['a1', 'pen', 3], ['b2', 'ink', 10], ['c3', 'pad', 7]]
An odd limit keeps the extra row at the start:
>>> big = Daf(cols=['n'], lol=[[i] for i in range(10)])
>>> big.daf_to_lol_summary(max_rows=3)
[['n'], [0], [1], ['...'], [9]]
dict_to_md ¶
dict_to_md(da, cols=None, just='<<')
Show a dict as a two column Markdown table, for looking at it.
This is a static method. Use it as print(Daf.dict_to_md(my_da)). The keys are
in the first column and the values in the second.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
da
|
T_da
|
The dict. |
required |
cols
|
T_ls | None
|
The two column names. Default |
None
|
just
|
str
|
The justification of the two columns. |
'<<'
|
Returns:
| Type | Description |
|---|---|
str
|
The Markdown text. |
Examples:
A dict, as a table of keys and values, left justified:
>>> print(Daf.dict_to_md({'pen': 3, 'ink': 'out of stock'}))
| key | value |
| :-- | :----------- |
| pen | 3 |
| ink | out of stock |
Other names for the two columns, and right justified:
>>> print(Daf.dict_to_md({'pen': 3, 'ink': 'out of stock'}, cols=['item', 'qty'], just='>>'))
| item | qty |
| ---: | -----------: |
| pen | 3 |
| ink | out of stock |
__str__ ¶
__str__()
Show the Daf as a Markdown table.
The table shows at most md_max_rows rows and md_max_cols columns, 10 by
default. Larger tables show the first five and the last five, with ...
between them. A summary line with the size and keyfield follows the table.
Use md_daf_table_snippet() for control over the output.
Returns:
| Type | Description |
|---|---|
str
|
The Markdown text. |
Examples:
Create a Daf of 12 people, and print it. It shows the first five rows and the last five:
>>> daf = Daf(cols=['id', 'age'], lol=[[f'p{i:02}', 20 + 3 * i] for i in range(12)])
>>> print(daf)
| id | age |
| --: | --: |
| p00 | 20 |
| p01 | 23 |
| p02 | 26 |
| p03 | 29 |
| p04 | 32 |
| ... | ... |
| p07 | 41 |
| p08 | 44 |
| p09 | 47 |
| p10 | 50 |
| p11 | 53 |
%% daf rows=12; cols=2; keyfield=''; name=''
The limits are attributes of the Daf:
>>> daf.md_max_rows = 4
>>> print(daf)
| id | age |
| --: | --: |
| p00 | 20 |
| p01 | 23 |
| ... | ... |
| p10 | 50 |
| p11 | 53 |
%% daf rows=12; cols=2; keyfield=''; name=''
__repr__ ¶
__repr__()
Show the Daf as a Markdown table, for the Python prompt.
This is the same text as str(), with a newline in front, so the table
starts at the left margin when it is echoed at the prompt.
Returns:
| Type | Description |
|---|---|
str
|
The Markdown text. |
Examples:
Create a small Daf of items in stock, and echo it at the prompt to see it as a table:
>>> daf = Daf(cols=['id', 'qty'], keyfield='id', lol=[['a1', 3], ['b2', 10]])
>>> daf
| id | qty |
| -: | --: |
| a1 | 3 |
| b2 | 10 |
%% daf rows=2; cols=2; keyfield='id'; name=''
__format__ ¶
__format__(format_spec)
Format a Daf that holds one cell.
With no format spec this is the same as str(). With a spec, the Daf must
have exactly one cell. A number is formatted with the spec. Anything else
is converted with str().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
format_spec
|
str
|
A format spec such as |
required |
Returns:
| Type | Description |
|---|---|
str
|
The formatted text. |
Raises:
| Type | Description |
|---|---|
ValueError
|
A spec is given and the Daf does not have exactly one cell. |
Examples:
Format a Daf of one cell in an f-string or with format(), with a format spec:
>>> format(Daf(cols=['height_m'], lol=[[1.684]]), '.2f')
'1.68'