amos.mungers
¶
Techniques that change what is in columns, usually before data is studied.
These are techniques of the "wrangler" stage of a project. Cleaners (see the
cleaners module) change which rows and columns there are. Mungers change
what is in the columns, or make new columns from them, without adding or
removing rows. Each one changes a whole column at once with the vectorized
methods of pandas (such as those of Series.str), so they are fast even
with a lot of data. Like cleaners, mungers learn nothing from the data that
could leak from the test rows into the training rows, so they are safe to use
before the data is split.
Parsers (see the parsers module) search text for patterns and make
columns of what they find.
Classes:
| Name | Description |
|---|---|
AutoCategorize |
Makes columns with few unique values categorical. |
Coalesce |
Takes the first value that is not missing from several columns. |
CombineFlags |
Combines flags into one: whether any or all are true, or how many are. |
ConvertTypes |
Changes the data types of columns. |
DeriveColumns |
Makes columns from expressions of other columns, such as "a / b". |
HtmlToText |
Converts columns of HTML or XML to plain text. |
MapValues |
Replaces values with others, such as "N/A" with a missing value. |
Munger |
Base class for techniques that change the values in columns. |
NormalizeText |
Normalizes the spaces, case, accents, and punctuation of text. |
SetKinds |
Sets the kind of each column, with the smallest type that holds it. |
StripText |
Trims spaces from text, and optionally makes it lowercase. |
AutoCategorize(contents=None, name='', parameters=dict())
dataclass
¶
Bases: Munger
Makes columns with few unique values categorical.
Text and number columns with threshold unique values or fewer become the
pandas "category" type, so they are encoded (rather than scaled) by the
analyst. Boolean columns are not changed.
munge(data, columns=None, threshold=None, **kwargs)
¶
Makes columns with threshold unique values or fewer categorical.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
the data to change. |
required |
columns
|
Sequence[str] | None
|
columns to check. Defaults to |
None
|
threshold
|
int | None
|
most unique values that a categorical column can have.
Defaults to |
None
|
**kwargs
|
Any
|
not used. |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
The data, with categorical columns. |
Source code in src/amos/wrangler/mungers/_types.py
Coalesce(contents=None, name='', parameters=dict())
dataclass
¶
Bases: Munger
Takes the first value that is not missing from several columns.
This combines columns that hold the same information from different sources, such as a date from a case's own data and a date found in its text: the first column is used where it has a value, and the next column fills in where it does not, and so on.
munge(data, *, columns=None, name=None, **kwargs)
¶
Makes a column of the first value in columns that is not missing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
the data to change. |
required |
columns
|
Sequence[str] | None
|
the columns to take values from, in order of preference.
Defaults to |
None
|
name
|
str | None
|
name of the column to make. Defaults to |
None
|
**kwargs
|
Any
|
not used. |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
The data, with the combined column. It is missing only where every
one of |
Source code in src/amos/wrangler/mungers/_values.py
CombineFlags(contents=None, name='', parameters=dict())
dataclass
¶
Bases: Munger
Combines flags into one: whether any or all are true, or how many are.
For example, a review mentions a problem if any of its flags of problems
("problem_price", "problem_shipping", and so on) are true. Flags are boolean
columns or numbers (where 0 is false), such as those that parse_flags
makes. A missing value is false.
munge(data, *, columns=None, name=None, how='any', **kwargs)
¶
Makes a column that combines the flags in columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
the data to change. |
required |
columns
|
Sequence[str] | None
|
the flags to combine. Defaults to |
None
|
name
|
str | None
|
name of the column to make. It is needed if there are
|
None
|
how
|
str
|
"any" (true if any flag is true), "all" (true if every flag is true), or "count" (the number of flags that are true). Defaults to "any". |
'any'
|
**kwargs
|
Any
|
not used. |
{}
|
Raises:
| Type | Description |
|---|---|
TypeError
|
if a column is not a flag. |
ValueError
|
if |
Returns:
| Type | Description |
|---|---|
DataFrame
|
The data, with the combined column: a boolean column, or whole numbers for "count". |
Source code in src/amos/wrangler/mungers/_values.py
ConvertTypes(contents=None, name='', parameters=dict())
dataclass
¶
Bases: Munger
Changes the data types of columns.
Wraps
pandas.DataFrame.astype
from pandas.
munge(data, types=None, **kwargs)
¶
Changes the type of each column in types.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
the data to change. |
required |
types
|
Mapping[str, Any] | None
|
|
None
|
**kwargs
|
Any
|
not used. |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
The data, with the new types. |
Source code in src/amos/wrangler/mungers/_types.py
DeriveColumns(contents=None, name='', parameters=dict())
dataclass
¶
Bases: Munger
Makes columns from expressions of other columns, such as "a / b".
The expressions are "expressions", a dict of the names of the new
columns and their expressions, and any other parameter, whose name is the
name of a new column and whose value is its expression (as in
"victim_under_eighteen = victim_age < 18"). Words that are not columns are
values, so they need no quotes, as in "offender_race == B" (see
utilities.quote_bare_values).
Wraps
pandas.DataFrame.eval
from pandas.
munge(data, *, expressions=None, **named)
¶
Makes a column from each expression, in order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
the data to change. |
required |
expressions
|
Mapping[str, str] | None
|
|
None
|
**named
|
str
|
more expressions, by the names of the columns to make,
which are made after those in |
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
if an expression is an assignment (such as "a = b"), rather than an expression. |
Returns:
| Type | Description |
|---|---|
DataFrame
|
The data, with the new columns. |
Source code in src/amos/wrangler/mungers/_values.py
HtmlToText(contents=None, name='', parameters=dict())
dataclass
¶
Bases: Munger
Converts columns of HTML or XML to plain text.
Each value is converted as amos.mungers.html_to_text converts it:
paragraphs and other blocks are put on lines of their own, character
references (such as "&") become characters, and the text of scripts,
styles, and page numbers inserted by publishers is left out. Text without
tags is kept as it is (except for its character references).
Wraps
html.parser.HTMLParser
from Python.
munge(data, *, columns=None, skipped_tags=None, skipped_classes=None, block_tags=None, workers=1, **kwargs)
¶
Converts the markup in columns to plain text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
the data to change. |
required |
columns
|
Sequence[str] | None
|
columns to change. Defaults to |
None
|
skipped_tags
|
Iterable[str] | None
|
tags whose text is left out. Defaults to |
None
|
skipped_classes
|
Iterable[str] | None
|
values of the "class" attribute of elements
whose text is left out. Defaults to |
None
|
block_tags
|
Iterable[str] | None
|
tags that start a new line. Defaults to |
None
|
workers
|
int
|
how many processes convert the text at once, which helps with many long documents. -1 uses every core. Defaults to 1. |
1
|
**kwargs
|
Any
|
not used. |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
The data, with plain text. Empty text becomes a missing value, and missing values stay missing. |
Source code in src/amos/wrangler/mungers/_markup.py
MapValues(contents=None, name='', parameters=dict())
dataclass
¶
Bases: Munger
Replaces values with others, such as "N/A" with a missing value.
Only whole values that are the same as one in values are replaced (use
parse_replace to change part of the text). Other values are kept. A
categorical column stays categorical.
Without "values", each column is changed by its map or function in
value_maps, which a subclass sets. A package built on amos can give
the meanings of its codes once (such as "W" for "white"), and every
project can then map them by naming the subclass, with or without
"columns". A function is applied to each value that is not missing. For
example:
@dataclasses.dataclass
class MapRaceCodes(amos.mungers.MapValues):
value_maps: ClassVar[dict[str, Any]] = {
'offender_race': {'W': 'white', 'B': 'black'},
'victim_race': {'W': 'white', 'B': 'black'},
'state': str.upper}
munge(data, *, columns=None, values=None, **kwargs)
¶
Replaces the values in columns that are keys of values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
the data to change. |
required |
columns
|
Sequence[str] | str | None
|
columns to change. Defaults to |
None
|
values
|
Mapping[Any, Any] | None
|
|
None
|
**kwargs
|
Any
|
not used. |
{}
|
Raises:
| Type | Description |
|---|---|
KeyError
|
if |
TypeError
|
if a map in |
Returns:
| Type | Description |
|---|---|
DataFrame
|
The data, with the new values. The type of a changed column is
found from its new values, as |
Source code in src/amos/wrangler/mungers/_values.py
Munger(contents=None, name='', parameters=dict())
dataclass
¶
Bases: Operation, ABC
Base class for techniques that change the values in columns.
A subclass writes a munge method, which takes the data and returns it
with changed or new columns, and the same rows. The dataset's history
records the columns whose values or types changed ("changed") and the new
columns ("created").
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
name used to refer to the technique in a workflow. Defaults to
an empty |
''
|
contents
|
str | Callable[..., Any] | None
|
not used by most mungers. Defaults to |
None
|
parameters
|
GenericDict
|
keyword arguments for |
dict()
|
apply(item, **kwargs)
¶
Changes the columns of item.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
item
|
Dataset
|
the dataset to change. |
required |
**kwargs
|
Any
|
parameters for |
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
if |
Returns:
| Type | Description |
|---|---|
Dataset
|
The changed dataset. |
Source code in src/amos/wrangler/mungers/_base.py
munge(data, **kwargs)
abstractmethod
¶
Returns data with changed or new columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
the data to change. It may be changed in place. |
required |
**kwargs
|
Any
|
parameters for munging. |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
The changed data, with the same rows. |
Source code in src/amos/wrangler/mungers/_base.py
NormalizeText(contents=None, name='', parameters=dict())
dataclass
¶
Bases: Munger
Normalizes the spaces, case, accents, and punctuation of text.
Every run of spaces, tabs, and line breaks becomes one space, and spaces are trimmed from both ends. It can also change the case of the text, remove accents (so "é" becomes "e"), and remove punctuation (so "U.S." becomes "US" and "O'Brien" becomes "OBrien"). This makes text that was written differently the same, so it can be counted, compared, or encoded as one value.
munge(data, *, columns=None, case=None, remove_accents=False, remove_punctuation=False, **kwargs)
¶
Normalizes the text in columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
the data to change. |
required |
columns
|
Sequence[str] | None
|
columns to change. Defaults to |
None
|
case
|
str | None
|
"lower", "upper", or "title" (which capitalizes each word).
Defaults to |
None
|
remove_accents
|
bool
|
whether to remove accents from letters. Defaults to
|
False
|
remove_punctuation
|
bool
|
whether to remove punctuation. Defaults to
|
False
|
**kwargs
|
Any
|
not used. |
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
if |
Returns:
| Type | Description |
|---|---|
DataFrame
|
The data, with normalized text. Empty text becomes a missing value. |
Source code in src/amos/wrangler/mungers/_text.py
SetKinds(contents=None, name='', parameters=dict())
dataclass
¶
Bases: Munger
Sets the kind of each column, with the smallest type that holds it.
The kinds are "dummy" (0 and 1, or false and true), "categorical", and
"numerical". Each is a parameter that lists its columns, as in "dummy =
rape, murder". A column that is not listed gets the kind of its values:
a boolean column, or a column of numbers that are all 0 or 1 (with none
missing), is a dummy; any other column of numbers is numerical; and a
categorical column, or text with options._CATEGORY_THRESHOLD unique
values or fewer, is categorical. Other columns (such as dates and longer
text) and the groups are not changed unless they are listed. If the label
is not listed, it is a dummy when it is classified and its values are
booleans (or 0 and 1), and is otherwise not changed.
Each kind is stored in the smallest type that holds its values exactly:
- dummy:
int8, with 0 for false and 1 for true. - categorical: the
pandas"category" type, whose codes are the smallest integer type that holds them. - numerical: the smallest signed integer type (such as
int8) if every value is a whole number and none is missing. Otherwisefloat32if it holds every value to about 7 significant digits, andfloat64if it does not.
The kinds are kept in Dataset.kinds, so a dummy is one of the dataset's
booleans (not its numerics). Arithmetic on small integer types can
overflow (int8 only holds -128 to 127), so make new columns from
numbers (as derive_columns does) before setting their kinds.
apply(item, **kwargs)
¶
Sets the kinds of the columns of item, and keeps them in kinds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
item
|
Dataset
|
the dataset to change. |
required |
**kwargs
|
Any
|
the columns of each kind ("dummy", "categorical", and "numerical"). |
{}
|
Returns:
| Type | Description |
|---|---|
Dataset
|
The changed dataset. |
Source code in src/amos/wrangler/mungers/_types.py
munge(data, *, kinds=None, **listed)
¶
Gives each column the smallest type of its kind.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
the data to change. |
required |
kinds
|
Mapping[str, str] | None
|
the kind of each column to change ("booleans",
"categoricals", or "numerics"), as |
None
|
**listed
|
Any
|
the columns of each kind ("dummy", "categorical", and "numerical"). |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
The data, with the new types. |
Source code in src/amos/wrangler/mungers/_types.py
StripText(contents=None, name='', parameters=dict())
dataclass
¶
Bases: Munger
Trims spaces from text, and optionally makes it lowercase.
Wraps
pandas.Series.str.strip
from pandas.
munge(data, *, columns=None, lowercase=False, **kwargs)
¶
Trims spaces from the text in columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
the data to change. |
required |
columns
|
Sequence[str] | None
|
columns to change. Defaults to |
None
|
lowercase
|
bool
|
whether to make the text lowercase too. Defaults to
|
False
|
**kwargs
|
Any
|
not used. |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
The data, with trimmed text. Empty text becomes a missing value. |
Source code in src/amos/wrangler/mungers/_text.py
html_to_text(markup, *, skipped_tags=None, skipped_classes=None, block_tags=None)
¶
Converts HTML or XML to plain text.
Paragraphs and other blocks are put on lines of their own, character references (such as "§") become characters, and the text of scripts, styles, and page numbers inserted by publishers ("star pagination") is left out. Markup that is not well formed (such as a tag that is never closed) is read as a browser would.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
markup
|
str
|
HTML or XML. Text without tags is returned unchanged, except that character references are converted. |
required |
skipped_tags
|
Iterable[str] | None
|
tags whose text is left out (with the text of every
element inside them). Defaults to |
None
|
skipped_classes
|
Iterable[str] | None
|
values of the "class" attribute of elements whose
text is left out. Defaults to |
None
|
block_tags
|
Iterable[str] | None
|
tags that start a new line. Defaults to |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The text, with blank lines removed and the spaces of each line collapsed and trimmed. |