将多个Pandas数据帧列进行分组加权平均并返回数据帧

3

我的问题和这个问题有关。但是那里的解决方案对我不起作用。

我有一个数据框df,如下所示。我想按buildingday分组,以counts为权重计算elevationwidth的加权平均值。我该怎么做?

#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
4个回答

4
您可以使用 reindexrepeat 的技巧。
df.reindex(df.index.repeat(df.counts)).drop('counts',1).\
     groupby(['building','day'],as_index=False).mean()
Out[110]: 
  building         day  elevation  width
0       A1  2019-07-02       7.10   2.00
1       A1  2019-07-03       7.44   2.91

1
我猜应该有更好的方法,但这个可以实现:
df = pd.DataFrame({
  'building': ['A1', 'A1', 'A1', 'A1'],
  'day': ['2019-07-02', '2019-07-02', '2019-07-03', '2019-07-03'],
  'id': ['alak', 'ldau', 'lauid', '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 = df.set_index(['building','day'])
sum_count = df.groupby(['building','day']).counts.sum()
df['w_elevation'] = df.elevation*df.counts /sum_count
df['w_width'] = df.width*df.counts / sum_count
df.groupby(['building','day']).sum()

输出:

                     counts  elevation  width  w_elevation  w_width
building day                                                       
A1       2019-07-02       3       13.5    3.6         7.10     2.00
         2019-07-03      10       15.6    6.1         7.44     2.91

1
您可以按照以下方式进行操作:
df_sum= df.copy()
df_sum['elevation']*= df_sum['counts']
df_sum['width']*= df_sum['counts']

df_sum= df_sum.groupby(['building', 'day']).agg(dict(elevation=sum, width=sum, counts=sum))
df_sum['elevation']/= df_sum['counts']
df_sum['width']/= df_sum['counts']
df_sum.reset_index(inplace=True)
df_sum.drop('counts', axis='columns', inplace=True)

结果是:

这里放内容

  building         day  elevation  width
0       A1  2019-07-02       7.10   2.00
1       A1  2019-07-03       7.44   2.91

你使用.agg(dict..)单独求和,而不是直接使用sum,有什么原因吗?谢谢。 - Moondra
1
这只是因为还有一个不可相加的“id”。但是您可以在应用之前限制列。使用什么更多是品味问题。 - jottbe

1
如果您需要比之前的答案更详细的内容:
result = df

# normalize for the weight
result['elevation'] = result['elevation'] * result['counts']
result['width'] = result['width'] * result['counts']

# let's sum all values per our dimensions
result = result.groupby(['building', 'day']).sum()
# and the get the weighted averages
result['elevation'] = result['elevation'] / result['counts']
result['width'] = result['width'] / result['counts']

# final results
result[['elevation', 'width']] 

另一种说法是:

或者以另一种方式表达:

result = df

# first of all let's get the sum of counts by building and day
# the indexes will return useful later
result = result.set_index(['building', 'day'])
counts = result['counts'].groupby(['building', 'day']).sum()

# let's normalize the values for elevation and width
result[['elevation', 'width']] = result[['elevation', 'width']].apply(lambda x: x * result['counts'])

# finally calculate the wigthed average
result = result[['elevation', 'width']].groupby(['building', 'day']).sum()
result = result[['elevation', 'width']].apply(lambda x: x / counts)

result

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接