class SubsetCallOp(base.CallOp):
"""A frame method on all columns or on the `columns` subset, with a new table as result.
`out = df[["x", "y"]].corr(method="spearman").reset_index(names="column")` (`then` is
the tail, `finish()` its execution). `columns` is never passed to the method.
"""
category = categories.STATS
icon = "mdi.chart-box-outline"
@classmethod
def call_args(cls, params: base.Params) -> tuple[list[Any], dict[str, Any]]:
args, kwargs = base.call_arguments(params, cls.positional, cls.always, ("columns",))
return args, {**cls.fixed, **kwargs}
@classmethod
def apply(cls, params: Any, *inputs: Frame) -> Frame:
frame = inputs[0]
if params.columns is not None:
missing = [c for c in params.columns if c not in frame.columns]
if missing:
raise base.OpError(f"unknown columns: {missing}")
frame = frame[params.columns]
args, kwargs = cls.call_args(params)
assert cls.method is not None
result = cls.finish(params, getattr(frame, cls.method)(*args, **kwargs))
if not frames.is_frame(result):
msg = f"{cls.id} returned {type(result).__name__}, not a frame"
raise base.OpError(msg)
return result
@classmethod
def to_code(cls, params: Any, inputs: Sequence[str], output: str) -> str:
source = inputs[0]
if params.columns is not None:
source = f"{source}[{base.literal(params.columns)}]"
args, kwargs = cls.call_args(params)
func = f"{source}.{cls.method}"
width = len(output) + 3 + len(cls.then) # the tail goes on the last line
call = base.format_call(func, list(map(base.literal, args)), kwargs, width)
return f"{output} = {call}{cls.then}"
@classmethod
def from_code(cls, stmt: ast.stmt, bound: Mapping[str, Any]) -> base.Match | None: # noqa: PLR0911
assign = base.assignment(stmt)
if assign is None:
return None
output, value = assign
if cls.then:
value = base.strip_tail(value, cls.then)
chain = series.unchain(value) if value is not None else None
if chain is None:
return None
root, links = chain
if not (isinstance(root, ast.Name) and root.id in bound and 1 <= len(links) <= 2): # noqa: PLR2004
return None
call = links[-1]
if call.kind != "call" or call.name != cls.method or "columns" in call.kwargs:
return None
try:
columns = series.item_key(links[0]) if len(links) == 2 else None # noqa: PLR2004
args, kwargs = call.literal_args()
except ValueError: # not literal: user code
return None
if columns is not None and not isinstance(columns, list):
return None
params = cls.params_from_call(args, {**kwargs, "columns": columns})
return None if params is None else base.Match(params, (root.id,), output)