(
table,
data: DataFrame,
values,
rows,
cols,
aggfunc,
kwargs,
observed: bool,
margins_name: Hashable = "All",
dropna: bool = True,
)
| 534 | |
| 535 | |
| 536 | def _generate_marginal_results( |
| 537 | table, |
| 538 | data: DataFrame, |
| 539 | values, |
| 540 | rows, |
| 541 | cols, |
| 542 | aggfunc, |
| 543 | kwargs, |
| 544 | observed: bool, |
| 545 | margins_name: Hashable = "All", |
| 546 | dropna: bool = True, |
| 547 | ): |
| 548 | margin_keys: list | Index |
| 549 | if len(cols) > 0: |
| 550 | # need to "interleave" the margins |
| 551 | table_pieces = [] |
| 552 | margin_keys = [] |
| 553 | |
| 554 | def _all_key(key): |
| 555 | return (key, margins_name) + ("",) * (len(cols) - 1) |
| 556 | |
| 557 | if len(rows) > 0: |
| 558 | margin = ( |
| 559 | data[rows + values] |
| 560 | .groupby(rows, observed=observed, dropna=dropna) |
| 561 | .agg(aggfunc, **kwargs) |
| 562 | ) |
| 563 | cat_axis = 1 |
| 564 | |
| 565 | for key, piece in table.T.groupby(level=0, observed=observed): |
| 566 | piece = piece.T |
| 567 | all_key = _all_key(key) |
| 568 | |
| 569 | piece[all_key] = margin[key] |
| 570 | |
| 571 | table_pieces.append(piece) |
| 572 | margin_keys.append(all_key) |
| 573 | else: |
| 574 | margin = ( |
| 575 | data[cols[:1] + values] |
| 576 | .groupby(cols[:1], observed=observed, dropna=dropna) |
| 577 | .agg(aggfunc, **kwargs) |
| 578 | .T |
| 579 | ) |
| 580 | |
| 581 | cat_axis = 0 |
| 582 | for key, piece in table.groupby(level=0, observed=observed): |
| 583 | if len(cols) > 1: |
| 584 | all_key = _all_key(key) |
| 585 | else: |
| 586 | all_key = margins_name |
| 587 | table_pieces.append(piece) |
| 588 | transformed_piece = margin[key].to_frame().T |
| 589 | if isinstance(piece.index, MultiIndex): |
| 590 | # We are adding an empty level |
| 591 | transformed_piece.index = MultiIndex.from_tuples( |
| 592 | [all_key], |
| 593 | names=[*piece.index.names, None], |
no test coverage detected