python - 如何在 panda 中使用需要唯一的列执行移动平均值?

标签 python pandas dataframe moving-average

我有一个如下所示的数据框:

          index       Player      Team      Matchup   Game_Date WL   Min   PTS   FGM   FGA   FG%  3PM  3PA   3P%  FTM   FTA   FT%  OREB  DREB   REB   AST  STL  BLK  TOV    PF  Plus_Minus  Triple_Double  Double_Double    FPT   2PA   2PM         2P% Home_Away
276100      1           John Long  TOR    TOR @ BOS  04/20/1997  W   6.0   0.0   0.0   3.0   0.0  0.0  1.0   0.0  0.0   0.0     0   0.0   0.0   0.0   1.0  0.0  0.0  0.0   0.0         2.0            0.0            0.0   1.50   2.0   0.0    0.000000      Away
276101      2       Walt Williams  TOR    TOR @ BOS  04/20/1997  W  29.0   7.0   3.0   9.0  33.3  1.0  2.0  50.0  0.0   0.0     0   3.0   3.0   3.0   2.0  2.0  1.0  1.0   3.0        20.0            0.0            0.0  19.75   7.0   2.0   28.571429      Away
276102      3            Todd Day  BOS  BOS vs. TOR  04/20/1997  L  36.0  22.0   8.0  17.0  47.1  4.0  8.0  50.0  2.0   2.0   100   8.0   8.0   6.0   4.0  0.0  0.0  3.0   8.0       -21.0            0.0            0.0  36.00   9.0   4.0   44.444444      Home
276103      4       Doug Christie  TOR    TOR @ BOS  04/20/1997  W  39.0  27.0   8.0  19.0  42.1  3.0  9.0  33.3  8.0   8.0   100   8.0   8.0   1.0   5.0  3.0  1.0  0.0   8.0        30.0            0.0            0.0  45.25  10.0   5.0   50.000000      Away
276104      5         Brett Szabo  BOS  BOS vs. TOR  04/20/1997  L  25.0   5.0   1.0   4.0  25.0  0.0  0.0     0  3.0   4.0  75.0   1.0   1.0   3.0   1.0  0.0  0.0  0.0   1.0       -11.0            0.0            0.0  10.25   4.0   1.0   25.000000      Home

我想添加一个新列,该列采用每个旧列并给出其 x 天移动平均值。但是,我想要每个独特的人的移动平均值。例如,约翰·朗 (John Long) 可以玩数百场比赛,每场比赛都在一个特定的日期进行。我希望他的移动平均数仅反射(reflect)他的表现。我查看了 pandas 中的 df.rolling() 函数,但我不知道如何制作它,因此它会单独查看每个玩家。任何帮助将不胜感激。

          Name    Date  Points  MA
0    Joe Smith  1-1-19      10  NA
1  Sam Simmons  1-1-19      20  NA
2    Joe Smith  1-2-19      30  20
3  Sam Simmons  1-2-19      40  30

最佳答案

您可以使用groupbyrollingmean,然后通过 join 添加新列:

df['Date'] = pd.to_datetime(df['Date'], format='%m-%d-%y')

s = df.set_index('Date').groupby('Name')['Points'].rolling(2, freq='D').mean().rename('MA')

df = df.join(s, on=['Name','Date'])
print (df)
          Name       Date  Points    MA
0    Joe Smith 2019-01-01      10   NaN
1  Sam Simmons 2019-01-01      20   NaN
2    Joe Smith 2019-01-02      30  20.0
3  Sam Simmons 2019-01-02      40  30.0

关于python - 如何在 panda 中使用需要唯一的列执行移动平均值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54176642/

相关文章:

python - Dask + pyinstaller 失败

python - 在 Pandas 中一起使用 loc 和 iloc

r - 按列值 >0 过滤多行

python - 将字符串中的每个单词读入 pandas 新行

python - 在 pandas 中使用 lstrip 时删除多余的字符

python - multiprocessing.Queue 的管道损坏错误

python - 根据条件从Python字典中选择特定范围的元素

python - 如何从 pandas.datetime 中提取小时数?

python - 使用 numpy.max/numpy.min 作为时间戳值

python - 在 pandas DataFrame 内的列表上使用 numpy.where (或 numpy.select)