My question is related to this one. However, the solution there isn't working for me.
I have a dataframe, df
, as shown below. I want to take the weighted averages of elevation
and width
with counts
as the weights, grouped by building
and day
. How can I do that?
#Sample data
import pandas as pd
df = pd.DataFrame({
'building': ['A1', 'A1', 'A1', 'A1'],
'day': ['2019-07-02', '2019-07-02', '2019-07-03', '2019-07-03'],
'id': ['alak', 'ldau', 'laud', 'lkdu'],
'counts': [1, 2, 3, 7],
'elevation': [5.7, 7.8, 8.7, 6.9],
'width':[1.2, 2.4, 3.4, 2.7]
})
df
building day id counts elevation width
0 A1 2019-07-02 alak 1 5.7 1.2
1 A1 2019-07-02 ldau 2 7.8 2.4
2 A1 2019-07-03 laud 3 8.7 3.4
3 A1 2019-07-03 lkdu 7 6.9 2.7
# What I want to get:
building day elevation width
0 A1 2019-07-02 7.1 2.0
1 A1 2019-07-03 7.4 2.9