class Downcast(base.Op):
id = "downcast"
title = _("Downcast numbers")
description = _("Store numeric columns in the smallest data type that holds their values.")
category = categories.CONVERSION
icon = "mdi.arrow-collapse-down"
class Params(base.Params):
columns: list[str] = _columns_field()
downcast: Literal["integer", "signed", "unsigned", "float"] = Field(
"integer", title=N_("Target type")
)
@classmethod
def apply(cls, params: Params, *inputs: Frame) -> Frame:
import pandas as pd
frame = inputs[0]
part = frame[params.columns].apply(pd.to_numeric, downcast=params.downcast)
return frame.assign(**part)
@classmethod
def to_code(cls, params: Params, inputs: Sequence[str], output: str) -> str:
frame = inputs[0]
part = f"{frame}[{base.literal(params.columns)}]"
call = f"{part}.apply(pd.to_numeric, downcast={base.literal(params.downcast)})"
return f"{output} = {frame}.assign(**{call})"
@classmethod
def from_code(cls, stmt: ast.stmt, bound: Mapping[str, Any]) -> base.Match | None:
assign = base.assignment(stmt)
if assign is None:
return None
output, value = assign
target = base.assign_target(value, bound)
if target is None:
return None
frame, kw = target
call = kw.value
if not (
kw.arg is None
and isinstance(call, ast.Call)
and isinstance(call.func, ast.Attribute)
and call.func.attr == "apply"
and isinstance(sub := call.func.value, ast.Subscript)
and isinstance(sub.value, ast.Name)
and sub.value.id == frame
and len(call.args) == 1
and base.dotted_name(call.args[0]) == "pd.to_numeric"
and [k.arg for k in call.keywords] == ["downcast"]
):
return None
try:
columns = base.literal_value(sub.slice)
downcast = base.literal_value(call.keywords[0].value)
except ValueError:
return None
return base.Match(cls.Params(columns=columns, downcast=downcast), (frame,), output)