python - 找到等于的运行平均值

标签 python pandas numpy rolling-average

假设我有一些与足球相关的数据

Date   Home     Away  HomeGoal AwayGoal TotalGoal
2019   Arsenal  MU     5        1        6
2019   MCity    Liv    2        2        4
2019   MU       Liv    3        4        7
2019   MCity    MU     0        0        0

我想创建一列数据来显示该球队最近两场比赛的平均进球数。 例如,在最后一行中,我想包含一列,显示 MU 在最近 2 场比赛中的平均进球数,即 = (1+3)/2 = 2。

python中有没有函数可以实现这个功能?

最佳答案

对于您的要求,您不关心球队是主队还是客队,只关心每场比赛进了多少球。试试这个:

# Rename the columns to make the unstacking operation a bit easier
# Always a good idea to specify an explicit `copy` when you intend
# to change the dataframe structure
>>> tmp = df[['Home', 'Away', 'HomeGoal', 'AwayGoal']].copy()

# Arrange the columns into a MultiIndex to make stacking easier
>>> tmp.columns = pd.MultiIndex.from_product([['Team', 'Goal'], ['Home', 'Away']])

# This is what `tmp` look like:

           Team      Goal     
      Home Away Home Away
0  Arsenal   MU    5    1
1    MCity  Liv    2    2
2       MU  Liv    3    4
3    MCity   MU    0    0

# And now the magic
>>> tmp.stack() \
        .groupby('Team').rolling(2).mean() \
        .groupby('Team').tail(1) \
        .droplevel([1,2])

# Result
         Goal
Team         
Arsenal   NaN
Liv       3.0
MCity     1.0
MU        1.5

其工作原理如下:

  • stack 取消透视 HomeAway,这样对于每场比赛,我们都有 2 行用于 Teams目标
  • groupby('Team').rolling(2).mean() 获取每支球队最近 2 场比赛的滚动平均进球数
  • groupby('Team').tail(1) 获取每个团队的最后一个滚动平均值
  • 此时,过渡数据帧的索引有 3 个级别:球队名称、比赛编号和上一场比赛的主/客场指示符。我们只关心第一个,所以我们会放弃另外两个。

关于python - 找到等于的运行平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60114174/

相关文章:

python - 从 sklearn 导入时出现 ImportError : cannot import name check_build

python - Python 中 txt 文件的数组/列表

python - 如何汇总pandas数据框中列上的行

python - 类型错误 : 'numpy.int64' object is not callable — What does that mean in laymans terms?

python - 对 numpy.unique() 感到困惑

python - plt.hist() vs np.histogram() - 意想不到的结果

python - 覆盖/溺爱的优化(覆盖__getattribute__/__getattr__)

python - 在 python 存储库名称和包名称中使用连字符/破折号

python - 相当于 python __getattr__/__setattr__ 的 scala

python - 将多行字符串转换为数据框