Skip to main content
Version: Python

weighted_avg_by

The weighted_avg_by method creates a new table containing the weighted average for each group.

Syntax

weighted_avg_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 average for all non-key columns (default).
  • ["X"] will output the weighted average of each group in column X.
  • ["X", "Y"] will output the weighted average of each group designated from the X and Y columns.

Returns

A new table containing the weighted average for each group.

Examples

In this example, weighted_avg_by returns the weighted average of the whole table. Because an average cannot be computed for the string column Letter, this column is dropped before applying weighted_avg_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_avg_by("Weight")

In this example, weighted_avg_by returns the weighted average, 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_avg_by(wcol="Weight", by="X")