最近n天熊猫的平均值

时间:2018-02-13 21:27:23

标签: python pandas pandas-groupby

我已经在各种锦标赛中获得了高尔夫球手及其高尔夫球赛的数据框(参见下面发布的df头词典)。我需要一种快速的计算方式,对于玩家玩的每一轮,他的平均笔画获得了#39; (SG)前n天,其中n是我决定的任何值。我会知道如何通过将数据帧转换为列表列表并迭代来实现这一点,但这将非常缓慢。理想情况下,我希望Pandas df中的额外列可以追溯到过去100天内玩家的平均SG'。

这就是我们正在使用的(数据帧头的词典):

{'Avg SG Player': {0: 0.4564491861877877,
  1: -0.170952417298073,
  2: 1.509033309098962,
  3: -1.7298114700775877,
  4: 1.7856746598995106},
 'Avg Score': {0: 69.53846153846153,
  1: 69.53846153846153,
  2: 69.53846153846153,
  3: 69.53846153846153,
  4: 69.53846153846153},
 'Date': {0: Timestamp('2003-01-23 00:00:00'),
  1: Timestamp('2003-01-23 00:00:00'),
  2: Timestamp('2003-01-23 00:00:00'),
  3: Timestamp('2003-01-23 00:00:00'),
  4: Timestamp('2003-01-23 00:00:00')},
 'Field Strength': {0: 0.08871540761770776,
  1: 0.08871540761770776,
  2: 0.08871540761770776,
  3: 0.08871540761770776,
  4: 0.08871540761770776},
 'Ind': {0: 0, 1: 1, 2: 2, 3: 3, 4: 4},
 'Overall SG': {0: 7.627176946079241,
  1: 5.627176946079241,
  2: 5.627176946079241,
  3: 4.627176946079241,
  4: 4.627176946079241},
 'Player': {0: 'Harrison Frazar',
  1: 'John Huston',
  2: 'David Toms',
  3: 'James H. McLean',
  4: 'Luke Donald'},
 'Round': {0: 'R1', 1: 'R1', 2: 'R1', 3: 'R1', 4: 'R1'},
 'Rounds Played': {0: 270, 1: 209, 2: 228, 3: 28, 4: 221},
 'SG on Field': {0: 7.538461538461533,
  1: 5.538461538461533,
  2: 5.538461538461533,
  3: 4.538461538461533,
  4: 4.538461538461533},
 'Score': {0: 62, 1: 64, 2: 64, 3: 65, 4: 65},
 'Tourn-Round': {0: '2003 Phoenix OpenR1',
  1: '2003 Phoenix OpenR1',
  2: '2003 Phoenix OpenR1',
  3: '2003 Phoenix OpenR1',
  4: '2003 Phoenix OpenR1'},
 'Tournament': {0: '2003 Phoenix Open',
  1: '2003 Phoenix Open',
  2: '2003 Phoenix Open',
  3: '2003 Phoenix Open',
  4: '2003 Phoenix Open'}}

EDITED

Dataframe基本上是这样的:

玩家 - 获得的圆形笔画日期(当天)

T Woods - 01-01-2010 - 5.4

R McIlroy - 01-01-2010 - 3.8

T Woods - 02-01-2010 - 0.4

有350,000行。我需要的是一个额外的列,给出了有关玩家在本轮日期前n(比如说100天)获得的平均击球次数。

所以如果下一行是:

Player-Date-Strokes获得(当天)

T Woods - 20-01-2018 - 3.2

我希望第四个(新)列,称之为“100天平均值”,为2.9((5.4 + 0.4)/ 2),因为这是Tiger前两轮的平均值在定义的时间范围内。

谢谢,

汤姆

1 个答案:

答案 0 :(得分:1)

这应该有效:

n = 10000

start_date = pd.to_datetime('today') - pd.Timedelta(n, unit='D')

df[df['Date'] >= start_date].groupby('Player')['Avg SG Player'].mean()

如果您想输入开始日期和结束日期:

start_date = pd.to_datetime('2005-12-01')
end_date = pd.to_datetime('2015-12-01')

df[(df['Date'] >= start_date) & (df['Date'] <= end_date)].groupby('Player')['Avg SG Player'].mean()