Skip to content

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, which checks every column.

None
threshold int | None

most unique values that a categorical column can have. Defaults to None, which uses options._CATEGORY_THRESHOLD (read when the munger is applied).

None
**kwargs Any

not used.

{}

Returns:

Type Description
DataFrame

The data, with categorical columns.

Source code in src/amos/wrangler/mungers/_types.py
def munge(
    self,
    data: pd.DataFrame,
    columns: Sequence[str] | None = None,
    threshold: int | None = None,
    **kwargs: Any) -> pd.DataFrame:
    """Makes columns with `threshold` unique values or fewer categorical.

    Args:
        data: the data to change.
        columns: columns to check. Defaults to `None`, which checks every
            column.
        threshold: most unique values that a categorical column can have.
            Defaults to `None`, which uses `options._CATEGORY_THRESHOLD`
            (read when the munger is applied).
        **kwargs: not used.

    Returns:
        The data, with categorical columns.

    """
    if threshold is None:
        threshold = options._CATEGORY_THRESHOLD
    for column in utilities.select_columns(data, columns):
        values = data[column]
        if pd.api.types.is_bool_dtype(values.dtype):
            continue
        if values.nunique(dropna = True) <= threshold:
            data[column] = values.astype('category')
    return data

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, which changes nothing.

None
name str | None

name of the column to make. Defaults to None, in which case it is the first of columns, whose missing values are filled in from the others.

None
**kwargs Any

not used.

{}

Returns:

Type Description
DataFrame

The data, with the combined column. It is missing only where every one of columns is.

Source code in src/amos/wrangler/mungers/_values.py
def munge(
    self,
    data: pd.DataFrame,
    *,
    columns: Sequence[str] | None = None,
    name: str | None = None,
    **kwargs: Any) -> pd.DataFrame:
    """Makes a column of the first value in `columns` that is not missing.

    Args:
        data: the data to change.
        columns: the columns to take values from, in order of preference.
            Defaults to `None`, which changes nothing.
        name: name of the column to make. Defaults to `None`, in which
            case it is the first of `columns`, whose missing values are
            filled in from the others.
        **kwargs: not used.

    Returns:
        The data, with the combined column. It is missing only where every
            one of `columns` is.

    """
    names = utilities.select_columns(data, columns or [])
    if not names:
        return data
    # Values of several types are combined as objects, and `infer_objects`
    # then finds the type that suits them all.
    first = data[names].astype(object).bfill(axis = 1).iloc[:, 0]
    data[name or names[0]] = first.infer_objects()
    return data

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, which changes nothing.

None
name str | None

name of the column to make. It is needed if there are columns. Defaults to None.

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 how is not one of the ways above, or there is no name.

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
def munge(
    self,
    data: pd.DataFrame,
    *,
    columns: Sequence[str] | None = None,
    name: str | None = None,
    how: str = 'any',
    **kwargs: Any) -> pd.DataFrame:
    """Makes a column that combines the flags in `columns`.

    Args:
        data: the data to change.
        columns: the flags to combine. Defaults to `None`, which changes
            nothing.
        name: name of the column to make. It is needed if there are
            `columns`. Defaults to `None`.
        how: "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".
        **kwargs: not used.

    Raises:
        TypeError: if a column is not a flag.
        ValueError: if `how` is not one of the ways above, or there is no
            `name`.

    Returns:
        The data, with the combined column: a boolean column, or whole
            numbers for "count".

    """
    names = utilities.select_columns(data, columns or [])
    if not names:
        return data
    if how not in _HOWS:
        message = f'how must be one of {sorted(_HOWS)}, not {how!r}'
        raise ValueError(message)
    if name is None:
        message = f'{self.name!r} needs a name for the column it makes'
        raise ValueError(message)
    flags = np.column_stack([_truth(data[c], c) for c in names])
    if how == 'count':
        data[name] = flags.sum(axis = 1).astype('int64')
    else:
        data[name] = np.asarray(
            flags.any(axis = 1) if how == 'any' else flags.all(axis = 1))
    return data

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

dict mapping column names to pandas data types (such as "category", "float", or "boolean"). Defaults to None, which changes nothing.

None
**kwargs Any

not used.

{}

Returns:

Type Description
DataFrame

The data, with the new types.

Source code in src/amos/wrangler/mungers/_types.py
def munge(
    self,
    data: pd.DataFrame,
    types: Mapping[str, Any] | None = None,
    **kwargs: Any) -> pd.DataFrame:
    """Changes the type of each column in `types`.

    Args:
        data: the data to change.
        types: `dict` mapping column names to `pandas` data types (such as
            "category", "float", or "boolean"). Defaults to `None`, which
            changes nothing.
        **kwargs: not used.

    Returns:
        The data, with the new types.

    """
    return data.astype(dict(types or {}))

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

dict mapping the names of the columns to make to pandas expressions of other columns, such as "sales / employees" or "age >= 18" (see pandas.DataFrame.eval). Column names with spaces go inside backticks. An expression can use the columns made before it. Defaults to None.

None
**named str

more expressions, by the names of the columns to make, which are made after those in expressions.

{}

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
def munge(
    self,
    data: pd.DataFrame,
    *,
    expressions: Mapping[str, str] | None = None,
    **named: str) -> pd.DataFrame:
    """Makes a column from each expression, in order.

    Args:
        data: the data to change.
        expressions: `dict` mapping the names of the columns to make to
            `pandas` expressions of other columns, such as "sales /
            employees" or "age >= 18" (see `pandas.DataFrame.eval`). Column
            names with spaces go inside backticks. An expression can use
            the columns made before it. Defaults to `None`.
        **named: more expressions, by the names of the columns to make,
            which are made after those in `expressions`.

    Raises:
        ValueError: if an expression is an assignment (such as "a = b"),
            rather than an expression.

    Returns:
        The data, with the new columns.

    """
    for name, expression in {**dict(expressions or {}), **named}.items():
        values = data.eval(
            utilities.quote_bare_values(str(expression), data))
        if isinstance(values, pd.DataFrame):
            message = (
                f'{expression!r} is an assignment: name the column in the '
                f'keys of the expressions instead'
            )
            raise ValueError(message)  # noqa: TRY004
        data[name] = values
    return data

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, which changes every text column.

None
skipped_tags Iterable[str] | None

tags whose text is left out. Defaults to None, which leaves out "script", "style", and "page-number".

None
skipped_classes Iterable[str] | None

values of the "class" attribute of elements whose text is left out. Defaults to None, which leaves out the page numbers that publishers insert ("star-pagination" and "page-label").

None
block_tags Iterable[str] | None

tags that start a new line. Defaults to None, which uses the blocks of HTML (such as "p", "div", and "li") and of the XML of some publishers (such as "opinion").

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
def munge(
    self,
    data: pd.DataFrame,
    *,
    columns: Sequence[str] | None = None,
    skipped_tags: Iterable[str] | None = None,
    skipped_classes: Iterable[str] | None = None,
    block_tags: Iterable[str] | None = None,
    workers: int = 1,
    **kwargs: Any) -> pd.DataFrame:
    """Converts the markup in `columns` to plain text.

    Args:
        data: the data to change.
        columns: columns to change. Defaults to `None`, which changes every
            text column.
        skipped_tags: tags whose text is left out. Defaults to `None`,
            which leaves out "script", "style", and "page-number".
        skipped_classes: values of the "class" attribute of elements
            whose text is left out. Defaults to `None`, which leaves out
            the page numbers that publishers insert ("star-pagination"
            and "page-label").
        block_tags: tags that start a new line. Defaults to `None`, which
            uses the blocks of HTML (such as "p", "div", and "li") and of
            the XML of some publishers (such as "opinion").
        workers: how many processes convert the text at once, which
            helps with many long documents. -1 uses every core. Defaults
            to 1.
        **kwargs: not used.

    Returns:
        The data, with plain text. Empty text becomes a missing value,
            and missing values stay missing.

    """
    convert = functools.partial(
        html_to_text,
        skipped_tags = skipped_tags,
        skipped_classes = skipped_classes,
        block_tags = block_tags)
    names = _text_columns(data) if columns is None else (
        utilities.select_columns(data, columns))
    for column in names:
        text = _text(data, column, self.name)
        present = text.notna().to_numpy()
        values = text[present].tolist()
        if workers == 1 or len(values) <= 1:
            converted = [convert(value) for value in values]
        else:
            joblib = importlib.import_module('joblib')
            parts = np.array_split(
                np.arange(len(values)),
                min(len(values), joblib.effective_n_jobs(workers)))
            pieces = joblib.Parallel(n_jobs = workers)(
                joblib.delayed(_convert_all)(
                    [values[i] for i in part], convert)
                for part in parts)
            converted = [value for piece in pieces for value in piece]
        result = text.copy()
        result[present] = converted
        data[column] = result.mask(result == '')
    return data

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, which changes every column if values is given, and otherwise every column of value_maps that is in the data.

None
values Mapping[Any, Any] | None

dict mapping values to the values that replace them. None makes a value missing. Defaults to None, in which case each column is changed by its map or function in value_maps.

None
**kwargs Any

not used.

{}

Raises:

Type Description
KeyError

if values is not given and a column in columns has no map or function in value_maps.

TypeError

if a map in value_maps is neither a mapping nor callable.

Returns:

Type Description
DataFrame

The data, with the new values. The type of a changed column is found from its new values, as pandas does.

Source code in src/amos/wrangler/mungers/_values.py
def munge(
    self,
    data: pd.DataFrame,
    *,
    columns: Sequence[str] | str | None = None,
    values: Mapping[Any, Any] | None = None,
    **kwargs: Any) -> pd.DataFrame:
    """Replaces the values in `columns` that are keys of `values`.

    Args:
        data: the data to change.
        columns: columns to change. Defaults to `None`, which changes
            every column if `values` is given, and otherwise every column
            of `value_maps` that is in the data.
        values: `dict` mapping values to the values that replace them.
            `None` makes a value missing. Defaults to `None`, in which
            case each column is changed by its map or function in
            `value_maps`.
        **kwargs: not used.

    Raises:
        KeyError: if `values` is not given and a column in `columns` has
            no map or function in `value_maps`.
        TypeError: if a map in `value_maps` is neither a mapping nor
            callable.

    Returns:
        The data, with the new values. The type of a changed column is
            found from its new values, as `pandas` does.

    """
    if values:
        mapping = dict(values)
        for column in utilities.select_columns(data, columns):
            data[column] = _recode(data[column], mapping)
        return data
    if columns is None:
        names = [c for c in self.value_maps if c in data.columns]
    else:
        names = utilities.select_columns(data, columns)
    unknown = [c for c in names if c not in self.value_maps]
    if unknown:
        message = (
            f'{self.name} has no values for the columns {unknown}: pass '
            f'"values" or subclass MapValues with "value_maps" for them'
        )
        raise KeyError(message)
    for column in names:
        mapped = self.value_maps[column]
        if isinstance(mapped, Mapping):
            data[column] = _recode(data[column], dict(mapped))
        elif callable(mapped):
            data[column] = data[column].map(mapped, na_action = 'ignore')
        else:
            message = (
                f'the values for {column!r} must be a dict or a '
                f'function, not {type(mapped).__name__}'
            )
            raise TypeError(message)
    return data

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 str, which uses the snake case name of the class.

''
contents str | Callable[..., Any] | None

not used by most mungers. Defaults to None.

None
parameters GenericDict

keyword arguments for munge. Defaults to an empty dict.

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 munge.

{}

Raises:

Type Description
ValueError

if munge changed the rows or removed columns.

Returns:

Type Description
Dataset

The changed dataset.

Source code in src/amos/wrangler/mungers/_base.py
def apply(self, item: base.Dataset, **kwargs: Any) -> base.Dataset:
    """Changes the columns of `item`.

    Args:
        item: the dataset to change.
        **kwargs: parameters for `munge`.

    Raises:
        ValueError: if `munge` changed the rows or removed columns.

    Returns:
        The changed dataset.

    """
    after = self.munge(item.data.copy(), **kwargs)
    return base._change_columns(item, after, self.name, 'munger')

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
@abc.abstractmethod
def munge(self, data: pd.DataFrame, **kwargs: Any) -> pd.DataFrame:
    """Returns `data` with changed or new columns.

    Args:
        data: the data to change. It may be changed in place.
        **kwargs: parameters for munging.

    Returns:
        The changed data, with the same rows.

    """

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, which changes every text column.

None
case str | None

"lower", "upper", or "title" (which capitalizes each word). Defaults to None, which does not change the case.

None
remove_accents bool

whether to remove accents from letters. Defaults to False.

False
remove_punctuation bool

whether to remove punctuation. Defaults to False.

False
**kwargs Any

not used.

{}

Raises:

Type Description
ValueError

if case is not one of the cases above.

Returns:

Type Description
DataFrame

The data, with normalized text. Empty text becomes a missing value.

Source code in src/amos/wrangler/mungers/_text.py
def munge(
    self,
    data: pd.DataFrame,
    *,
    columns: Sequence[str] | None = None,
    case: str | None = None,
    remove_accents: bool = False,
    remove_punctuation: bool = False,
    **kwargs: Any) -> pd.DataFrame:
    """Normalizes the text in `columns`.

    Args:
        data: the data to change.
        columns: columns to change. Defaults to `None`, which changes every
            text column.
        case: "lower", "upper", or "title" (which capitalizes each word).
            Defaults to `None`, which does not change the case.
        remove_accents: whether to remove accents from letters. Defaults to
            `False`.
        remove_punctuation: whether to remove punctuation. Defaults to
            `False`.
        **kwargs: not used.

    Raises:
        ValueError: if `case` is not one of the cases above.

    Returns:
        The data, with normalized text. Empty text becomes a missing value.

    """
    if case is not None and case not in _CASES:
        message = f'case must be one of {sorted(_CASES)}, not {case!r}'
        raise ValueError(message)
    names = _text_columns(data) if columns is None else (
        utilities.select_columns(data, columns))
    for column in names:
        text = _text(data, column, self.name)
        if remove_accents:
            text = text.str.normalize('NFKD').str.replace(
                _ACCENTS, '', regex = True)
        if remove_punctuation:
            text = text.str.replace(_PUNCTUATION, '', regex = True)
        text = text.str.replace(_WHITESPACE, ' ', regex = True)
        if case is not None:
            text = getattr(text.str, case)()
        data[column] = _tidy(text)
    return data

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. Otherwise float32 if it holds every value to about 7 significant digits, and float64 if 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
def apply(self, item: base.Dataset, **kwargs: Any) -> base.Dataset:
    """Sets the kinds of the columns of `item`, and keeps them in `kinds`.

    Args:
        item: the dataset to change.
        **kwargs: the columns of each kind ("dummy", "categorical", and
            "numerical").

    Returns:
        The changed dataset.

    """
    kinds = _find_kinds(
        item.data,
        kwargs,
        label = item.label if item.has_label else None,
        task = item.task,
        groups = item.groups)
    item = super().apply(item, kinds = kinds)
    item.kinds.update(kinds)
    return item

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 apply finds them. Defaults to None, in which case they are found from listed, without a label.

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
def munge(
    self,
    data: pd.DataFrame,
    *,
    kinds: Mapping[str, str] | None = None,
    **listed: Any) -> pd.DataFrame:
    """Gives each column the smallest type of its kind.

    Args:
        data: the data to change.
        kinds: the kind of each column to change ("booleans",
            "categoricals", or "numerics"), as `apply` finds them.
            Defaults to `None`, in which case they are found from
            `listed`, without a label.
        **listed: the columns of each kind ("dummy", "categorical", and
            "numerical").

    Returns:
        The data, with the new types.

    """
    if kinds is None:
        kinds = _find_kinds(data, listed)
    for column, kind in kinds.items():
        data[column] = _shrink(data[column], column, kind)
    return data

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, which changes every text column.

None
lowercase bool

whether to make the text lowercase too. Defaults to False.

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
def munge(
    self,
    data: pd.DataFrame,
    *,
    columns: Sequence[str] | None = None,
    lowercase: bool = False,
    **kwargs: Any) -> pd.DataFrame:
    """Trims spaces from the text in `columns`.

    Args:
        data: the data to change.
        columns: columns to change. Defaults to `None`, which changes every
            text column.
        lowercase: whether to make the text lowercase too. Defaults to
            `False`.
        **kwargs: not used.

    Returns:
        The data, with trimmed text. Empty text becomes a missing value.

    """
    if columns is None:
        columns = _text_columns(data)
    for column in utilities.select_columns(data, columns):
        text = data[column].str.strip()
        if lowercase:
            text = text.str.lower()
        data[column] = text.mask(text == '')
    return data

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, which leaves out "script", "style", and "page-number".

None
skipped_classes Iterable[str] | None

values of the "class" attribute of elements whose text is left out. Defaults to None, which leaves out the page numbers that publishers insert ("star-pagination" and "page-label").

None
block_tags Iterable[str] | None

tags that start a new line. Defaults to None, which uses the blocks of HTML (such as "p", "div", and "li") and of the XML of some publishers (such as "opinion" and "footnote").

None

Returns:

Type Description
str

The text, with blank lines removed and the spaces of each line collapsed and trimmed.

Source code in src/amos/wrangler/mungers/_markup.py
def html_to_text(
    markup: str,
    *,
    skipped_tags: Iterable[str] | None = None,
    skipped_classes: Iterable[str] | None = None,
    block_tags: Iterable[str] | None = None) -> str:
    """Converts HTML or XML to plain text.

    Paragraphs and other blocks are put on lines of their own, character
    references (such as "&sect;") 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.

    Args:
        markup: HTML or XML. Text without tags is returned unchanged, except
            that character references are converted.
        skipped_tags: tags whose text is left out (with the text of every
            element inside them). Defaults to `None`, which leaves out
            "script", "style", and "page-number".
        skipped_classes: values of the "class" attribute of elements whose
            text is left out. Defaults to `None`, which leaves out the page
            numbers that publishers insert ("star-pagination" and
            "page-label").
        block_tags: tags that start a new line. Defaults to `None`, which
            uses the blocks of HTML (such as "p", "div", and "li") and of the
            XML of some publishers (such as "opinion" and "footnote").

    Returns:
        The text, with blank lines removed and the spaces of each line
            collapsed and trimmed.

    """
    if '<' not in markup:
        return html.unescape(markup)
    extractor = _TextExtractor(
        block_tags = _lowered(block_tags, _BLOCK_TAGS),
        skipped_tags = _lowered(skipped_tags, _SKIPPED_TAGS),
        skipped_classes = (
            _SKIPPED_CLASSES if skipped_classes is None
            else frozenset(_names(skipped_classes))))
    extractor.feed(markup)
    extractor.close()
    lines = ''.join(extractor.parts).splitlines()
    return '\n'.join(
        ' '.join(line.split()) for line in lines if line.strip())