# Frequency Weights in DataFrames

**URL:** <https://discourse.julialang.org/t/frequency-weights-in-dataframes/57379>\
**Category:** Data\
**Tags:** question, dataframes\
**Created:** [March 17, 2021, 1:15pm UTC](https://discourse.julialang.org/t/frequency-weights-in-dataframes/57379 "2021-03-17T13:15:38Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![drarnau](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/drarnau/32/4476_2.png) [@drarnau](https://discourse.julialang.org/u/drarnau)\
**Post date:** [March 17, 2021, 1:15pm UTC](https://discourse.julialang.org/t/frequency-weights-in-dataframes/57379/1 "2021-03-17T13:15:38Z")

</div>

Hello,

I need to compute a group mean using frequency weights and I do not know how to do it.

I know how to compute an un weighted mean:

```julia
using DataFrames

df = DataFrame(age = rand(25:30, 25), value = rand(25), fweight = rand(100_000:1_000_000, 25))

unweighted = combine(groupby(df, :age), :value => mean)

```

How can I do the same but indicating I want the mean to use the frequency weights in `:fweight`?

Thanks!

---

<div class="post-metadata">

**Author:** ![Skoffer](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/skoffer/32/378_2.png) [@Skoffer](https://discourse.julialang.org/u/Skoffer)\
**Post date:** [March 17, 2021, 1:20pm UTC](https://discourse.julialang.org/t/frequency-weights-in-dataframes/57379/2 "2021-03-17T13:20:05Z")

</div>

Maybe something like this?

```julia
combine(groupby(df, :age), [:value, :fweight] => ((x, y) -> sum(x .* y)/sum(y)) => :weight_mean)

```

---

<div class="post-metadata">

**Author:** ![nalimilan](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nalimilan/32/147_2.png) [@nalimilan](https://discourse.julialang.org/u/nalimilan)\
**Post date:** [March 17, 2021, 1:31pm UTC](https://discourse.julialang.org/t/frequency-weights-in-dataframes/57379/3 "2021-03-17T13:31:26Z")

</div>

You can also use the weighted mean defined in StatsBase:

```julia
combine(groupby(df, :age), [:value, :fweight] => ((x, y) -> mean(x, fweights(y))) => :weighted_mean)

```

If you use these weights repeatedly, you can also do `df.fweight = fweights(df.fweights)` once and then write `y` instead of `fweights(y)`.

See [https://juliastats.org/StatsBase.jl/latest/means/#Statistics.mean](https://juliastats.org/StatsBase.jl/latest/means/#Statistics.mean) for details.
