Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
201 changes: 42 additions & 159 deletions microdf/microdataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from microdf.microseries import (
MicroSeries,
MicroSeriesGroupBy,
_grouped_result_as_columns,
_pair_options,
_usable_pair,
_validate_frequency_weights,
Expand Down Expand Up @@ -717,7 +718,6 @@ def equals(self, other: "MicroDataFrame") -> bool:
equal_weights = self.weights.equals(other.weights)
return equal_values and equal_weights

@get_args_as_micro_series()
def groupby(self, by: Union[str, List], *args, **kwargs) -> "MicroDataFrameGroupBy":
"""Returns a GroupBy object with MicroSeriesGroupBy objects for each
column.
Expand All @@ -728,23 +728,19 @@ def groupby(self, by: Union[str, List], *args, **kwargs) -> "MicroDataFrameGroup
return: DataFrameGroupBy object with columns using weights
rtype: DataFrameGroupBy
"""
# Build the groupby on a *copy* that carries a ``__tmp_weights``
# column. We used to set this column on ``self`` directly, which
# permanently leaked the weight column onto the caller's
# DataFrame — any later ``df.sum()`` or ``list(df.columns)``
# would then include it.
staged = pd.DataFrame(self).copy()
staged["__tmp_weights"] = np.asarray(self.weights.values, dtype=float)
weight_column = "__tmp_weights"
while weight_column in staged.columns:
weight_column += "_"
staged[weight_column] = np.asarray(self.weights.values, dtype=float)
gb = staged.groupby(by, *args, **kwargs)
weights = copy.deepcopy(gb["__tmp_weights"])
for col in staged.columns: # df.groupby(...)[col]s use weights
res = gb[col]
res.__class__ = MicroSeriesGroupBy
res._init()
res.weights = weights
setattr(gb, col, res)
# Share the same grouping for values and weights. Only the final
# result needs to put group keys in columns for as_index=False.
indexed = copy.copy(gb)
indexed.as_index = True
columns = [col for col in self.columns if col not in gb.exclusions]
gb.__class__ = MicroDataFrameGroupBy
gb._init(by)
gb._init(indexed, indexed[weight_column], columns)
return gb

@get_args_as_micro_series()
Expand Down Expand Up @@ -874,161 +870,48 @@ def __repr__(self) -> str:


class MicroDataFrameGroupBy(pd.core.groupby.generic.DataFrameGroupBy):
def _init(self, by: Union[str, List]):
self._by = by
self.columns = list(self.obj.columns)
if isinstance(by, list):
for column in by:
self.columns.remove(column)
elif isinstance(by, str):
self.columns.remove(by)
self.columns.remove("__tmp_weights")
# Filter to only numeric columns
def _init(self, indexed_groupby, weights_groupby, columns):
self._indexed_groupby = indexed_groupby
self._weights_groupby = weights_groupby
self.numeric_columns = [
col for col in self.columns if pd.api.types.is_numeric_dtype(self.obj[col])
col for col in columns if pd.api.types.is_numeric_dtype(self.obj[col])
]
# Store reference to weights groupby for column selection
self._weights_groupby = copy.deepcopy(super().__getitem__("__tmp_weights"))
for fn_name in MicroSeries.SCALAR_FUNCTIONS:

def get_fn(name):
def fn(*args, **kwargs):
results = {}
for col in self.numeric_columns:
try:
results[col] = getattr(getattr(self, col), name)(
*args, **kwargs
)
except TypeError as exc:
# Skip columns whose dtype can't take this aggregation.
# Deliberately narrow: catching every Exception here also
# swallowed real errors (e.g. the ValueError from
# gini(negatives=...)) and returned a silently truncated
# result instead of raising.
logger.debug("skipping column %s in %s: %s", col, name, exc)
# Return plain DataFrame - aggregated results don't have
# per-row weights (weights were already applied)
return pd.DataFrame(results) if results else pd.DataFrame()

return fn

setattr(self, fn_name, get_fn(fn_name))
for fn_name in MicroSeries.VECTOR_FUNCTIONS:

def get_fn(name) -> Callable:
def fn(*args, **kwargs) -> Union[pd.Series, pd.DataFrame]:
results = {}
for col in self.numeric_columns:
try:
results[col] = getattr(getattr(self, col), name)(
*args, **kwargs
)
except TypeError as exc:
# Skip columns whose dtype can't take this aggregation.
# Deliberately narrow: catching every Exception here also
# swallowed real errors (e.g. the ValueError from
# gini(negatives=...)) and returned a silently truncated
# result instead of raising.
logger.debug("skipping column %s in %s: %s", col, name, exc)
# Return plain DataFrame - aggregated results don't have
# per-row weights (weights were already applied)
return pd.DataFrame(results) if results else pd.DataFrame()
def get_fn(name):
def fn(*args, **kwargs):
results = {}
for col in self.numeric_columns:
grouped = self._indexed_groupby[col]
grouped.__class__ = MicroSeriesGroupBy
grouped.weights = self._weights_groupby
grouped._init()
try:
results[col] = getattr(grouped, name)(*args, **kwargs)
except TypeError as exc:
logger.debug("skipping column %s in %s: %s", col, name, exc)
result = pd.DataFrame(results)
if not self.as_index and results:
return _grouped_result_as_columns(result)
return result

return fn
return fn

for fn_name in MicroSeries.FUNCTIONS:
setattr(self, fn_name, get_fn(fn_name))

def __getitem__(
self, key: Union[str, List]
) -> Union["MicroSeriesGroupBy", "MicroDataFrameGroupBy"]:
"""Select columns from the groupby object while preserving weights.

This ensures that operations like groupby(col)["y"].sum() or
groupby(col)[["y"]].sum() use weighted aggregation.

:param key: Column name or list of column names
:return: MicroSeriesGroupBy for single column, MicroDataFrameGroupBy
for multiple columns
"""
if isinstance(key, str):
# Single column - return MicroSeriesGroupBy
result = super().__getitem__(key)
"""Select grouped columns while preserving their row weights."""
result = super().__getitem__(key)
if isinstance(result, pd.core.groupby.generic.SeriesGroupBy):
indexed = None if self.as_index else self._indexed_groupby[key]
result.__class__ = MicroSeriesGroupBy
result._init()
result.weights = self._weights_groupby
return result
result._init(indexed)
else:
# Multiple columns - return a new MicroDataFrameGroupBy
# with only the selected columns
result = super().__getitem__(key)
result.__class__ = MicroDataFrameGroupBy
# Re-initialize with the subset of columns
result._by = self._by
result.columns = list(key) if hasattr(key, "__iter__") else [key]
result.numeric_columns = [
col
for col in result.columns
if pd.api.types.is_numeric_dtype(result.obj[col])
]
result._weights_groupby = self._weights_groupby
# Set up the column attributes as MicroSeriesGroupBy
for col in result.columns:
col_gb = super().__getitem__(col)
col_gb.__class__ = MicroSeriesGroupBy
col_gb._init()
col_gb.weights = self._weights_groupby
setattr(result, col, col_gb)
# Set up the scalar and vector functions
for fn_name in MicroSeries.SCALAR_FUNCTIONS:

def get_scalar_fn(name, res):
def fn(*args, **kwargs):
results = {}
for col in res.numeric_columns:
try:
results[col] = getattr(getattr(res, col), name)(
*args, **kwargs
)
except TypeError as exc:
# Skip columns whose dtype can't take this aggregation.
# Deliberately narrow: catching every Exception here also
# swallowed real errors (e.g. the ValueError from
# gini(negatives=...)) and returned a silently truncated
# result instead of raising.
logger.debug(
"skipping column %s in %s: %s", col, name, exc
)
# Return plain DataFrame - aggregated results don't
# have per-row weights (weights were already applied)
return pd.DataFrame(results) if results else pd.DataFrame()

return fn

setattr(result, fn_name, get_scalar_fn(fn_name, result))
for fn_name in MicroSeries.VECTOR_FUNCTIONS:

def get_vector_fn(name, res):
def fn(*args, **kwargs):
results = {}
for col in res.numeric_columns:
try:
results[col] = getattr(getattr(res, col), name)(
*args, **kwargs
)
except TypeError as exc:
# Skip columns whose dtype can't take this aggregation.
# Deliberately narrow: catching every Exception here also
# swallowed real errors (e.g. the ValueError from
# gini(negatives=...)) and returned a silently truncated
# result instead of raising.
logger.debug(
"skipping column %s in %s: %s", col, name, exc
)
# Return plain DataFrame - aggregated results don't
# have per-row weights (weights were already applied)
return pd.DataFrame(results) if results else pd.DataFrame()

return fn

setattr(result, fn_name, get_vector_fn(fn_name, result))
return result
result._init(
self._indexed_groupby, self._weights_groupby, result._selection_list
)
return result
106 changes: 49 additions & 57 deletions microdf/microseries.py
Original file line number Diff line number Diff line change
Expand Up @@ -1190,73 +1190,65 @@ def __repr__(self) -> str:
)


def _grouped_result_as_columns(result: pd.DataFrame) -> pd.DataFrame:
keys = result.iloc[:, :0].reset_index(allow_duplicates=True)
# An explicitly selected grouping column can also be a result column.
keys = keys.loc[:, ~keys.columns.isin(result.columns)]
return pd.concat([keys, result.reset_index(drop=True)], axis=1)


class MicroSeriesGroupBy(pd.core.groupby.generic.SeriesGroupBy):
def _init(self):
def _weighted_agg(name) -> Callable:
def via_micro_series(row, *args, **kwargs):
return getattr(MicroSeries(row.a, weights=row.w), name)(*args, **kwargs)
def _init(self, indexed_groupby=None):
grouped = self if indexed_groupby is None else indexed_groupby

def _weighted_agg(name) -> Callable:
fn = getattr(MicroSeries, name)

@wraps(fn)
def _weighted_agg_fn(*args, **kwargs) -> Union[pd.Series, pd.DataFrame]:
arrays = self.apply(np.array)
arrays = grouped.apply(np.array)
weights = self.weights.apply(np.array)
df = pd.DataFrame(dict(a=arrays, w=weights))
is_array = len(args) > 0 and hasattr(args[0], "__len__")
if (
name in MicroSeries.SCALAR_FUNCTIONS
or name in MicroSeries.AGNOSTIC_FUNCTIONS
and not is_array
):
result = df.agg(
lambda row: via_micro_series(row, *args, **kwargs),
axis=1,
)
elif (
name in MicroSeries.VECTOR_FUNCTIONS
or name in MicroSeries.AGNOSTIC_FUNCTIONS
and is_array
):
if name in MicroSeries.AGNOSTIC_FUNCTIONS and not df.empty:
# Concatenate values without keys: concat rejects missing
# MultiIndex keys even when groupby(dropna=False) retains
# them. Reuse the grouping levels and codes so missing
# labels keep the same representation as scalar results.
results = [
via_micro_series(row, *args, **kwargs)
for _, row in df.iterrows()
]
result = pd.concat(results)
group_index = (
df.index
if isinstance(df.index, pd.MultiIndex)
else pd.MultiIndex.from_arrays([df.index])
)
quantile_codes, quantile_levels = result.index.factorize(
sort=False
)
result.index = pd.MultiIndex(
levels=[*group_index.levels, quantile_levels],
codes=[
codes.repeat(len(results[0]))
for codes in group_index.codes
]
+ [quantile_codes],
names=[*df.index.names, result.index.name],
# Existing group codes are valid; checking would
# rewrite their retained missing labels to -1.
verify_integrity=False,
)
return result
result = df.apply(
lambda row: via_micro_series(row, *args, **kwargs),
axis=1,
)
return result.stack()
results = [
fn(MicroSeries(values, weights=group_weights), *args, **kwargs)
for values, group_weights in zip(arrays, weights)
]
vector = name in MicroSeries.VECTOR_FUNCTIONS
if name in MicroSeries.AGNOSTIC_FUNCTIONS:
q = args[0] if args else kwargs.get("q")
vector = np.ndim(q) != 0

if vector:
result = self._combine_vectors(arrays.index, results)
else:
result = pd.Series(results, index=arrays.index)
if not self.as_index:
return _grouped_result_as_columns(result.to_frame(self.obj.name))
return result

return _weighted_agg_fn

for fn_name in MicroSeries.FUNCTIONS:
setattr(self, fn_name, _weighted_agg(fn_name))

@staticmethod
def _combine_vectors(groups, results) -> pd.Series:
# Concatenate group results directly to retain NaN values and avoid
# padding shorter groups. The last level holds local row positions or q.
result = (
pd.concat([pd.Series(value) for value in results])
if results
else pd.Series(dtype=float)
)
if not isinstance(groups, pd.MultiIndex):
groups = pd.MultiIndex.from_arrays([groups])
lengths = [len(value) for value in results]
codes, levels = result.index.factorize(sort=False)
result.index = pd.MultiIndex(
levels=[*groups.levels, levels],
codes=[group_codes.repeat(lengths) for group_codes in groups.codes]
+ [codes],
names=[*groups.names, result.index.name],
# Keep the original codes for retained missing grouping keys.
verify_integrity=False,
)
return result
Loading
Loading