Skip to main content
Version: Python

weighted_sum_by

The weighted_sum_by method creates a new table containing the weighted sum for each group.

Syntax

weighted_sum_by(wcol: str, by: Union[str, list[str]] = None) -> Table

Parameters

ParameterTypeDescription
wcolstr

The name of the weight column.

by optionalUnion[str, list[str]]

The column(s) by which to group data.

  • [] returns the weighted sum for all non-key columns (default).
  • ["X"] will output the weighted sum of each group in column X.
  • ["X", "Y"] will output the weighted sum of each group designated from the X and Y columns.

Returns

A new table containing the weighted sum for each group.

Examples

In this example, weighted_sum_by returns the weighted sum of the whole table. Because a sum cannot be computed for the string column Letter, this column is dropped before applying weighted_sum_by.

from deephaven import new_table
from deephaven.column import string_col, int_col

source = new_table(
[
string_col("Letter", ["A", "B", "C", "D"]),
int_col("Weight", [2, 4, 6, 8]),
int_col("Numbers", [5, 10, 20, 9]),
int_col("Numbers2", [1, 2, 3, 4]),
]
)

result = source.drop_columns("Letter").weighted_sum_by("Weight")

In this example, weighted_sum_by returns the weighted sum, as grouped by X.

from deephaven import new_table
from deephaven.column import string_col, int_col

source = new_table(
[
int_col("Weight", [2, 4, 6, 8]),
int_col("Numbers", [5, 10, 20, 9]),
int_col("X", [1, 1, 2, 2]),
]
)

result = source.weighted_sum_by(wcol="Weight", by="X")