【问题标题】:Append average value of last three occurrences from pandas data frame从熊猫数据框中附加最后三个出现的平均值
【发布时间】:2018-12-12 03:01:02
【问题描述】:

我正在使用以下包含超过 54000 行的数据框:

我想要对数据框的每一列附加特定玩家与特定对手的平均“Draft_Kings_Points_Scored”。我已经在 Python 和 SQL 中尝试过,但似乎无法弄清楚。如果您知道这样做的方法,我将非常感谢您的帮助。

【问题讨论】:

  • 至少给我们可以复制的代码

标签: python sql pandas


【解决方案1】:

您可以将数据转换为时间序列,然后使用 pandas:

groupby().rolling().mean() 

这是代码。首先,制作一些数据进行测试:

import pandas as pd
import numpy as np
import string
from datetime import datetime

# set up matches, players,  tournament start and end
matches = 50000
players = list(string.ascii_uppercase)
start = datetime(2015, 1, 1).timestamp()
end = datetime(2018, 1, 1).timestamp()

# create a dataframe for testing
df = pd.DataFrame({
    'DATE': pd.to_datetime(np.random.randint(start, end, size=matches), unit='s'),
    'PLAYER': np.random.choice(players, matches),
    'OPPONENT': np.random.choice(players, matches),
    'SCORE': np.random.normal(100, 25, matches)
    })

# drop the cases where the player played themselve
df = df[df['PLAYER'] != df['OPPONENT']]

# make it a time series and ensure it is sorted
df.set_index('DATE', inplace=True)
df.sort_index(inplace=True)

df.head()

使用 groupby().rolling().mean() 就可以了:

df_rolling = df.groupby(['PLAYER', 'OPPONENT']).rolling(3).mean().reset_index()
df_rolling.head()

将其加入到包含所有列的原始数据并检查一个匹配项(A vs B)

df_final = pd.merge(df, df_rolling, on=['PLAYER', 'OPPONENT', 'DATE'], suffixes=['_RAW', '_AVG3'])
df_final[df_final['PLAYER'].eq('A') & df_final['OPPONENT'].eq('B')].tail(10)

【讨论】:

    猜你喜欢
    • 2018-05-15
    • 2018-10-26
    • 2018-11-16
    • 2021-03-10
    • 2021-08-20
    • 2020-04-26
    • 1970-01-01
    • 2013-02-14
    • 1970-01-01
    相关资源
    最近更新 更多