簡體   English   中英

熊貓:兩欄的條件滾動總和

[英]pandas:conditional rolling sum of two columns

我想計算一個衡量足球隊勢頭的指標,在​​這種情況下,某支球隊在最近3場比賽中得到的分數。 我的數據如下所示:

    HomeTeam    AwayTeam    H_Pts   A_Pts
    Barcelona   Getafe      3       0
    Levante     Barcelona   1       1
    Barcelona   Las Palmas  3       0
    Las Palmas  Barcelona   3       0
    Barcelona   Madrid      1       1

這只是巴塞羅那某些比賽的示例。 所以基本上我想要結束的是另外兩列(例如Home_Momentum,Away_Momentum),這些列加起來了這支特定球隊在最近3場比賽中獲得的積分(不包括當前的積分)。 所以它應該看起來像這樣:

    HomeTeam    AwayTeam    H_Pts   A_Pts    Home_Momentum    Away_Momentum
    Barcelona   Getafe      3       0        NaN              NaN
    Levante     Barcelona   1       1        NaN              NaN
    Barcelona   Las Palmas  3       0        NaN              NaN
    Las Palmas  Barcelona   3       0        x                7    
    Barcelona   Madrid      1       1        4                y

其中x(y)是拉斯帕爾馬斯(馬德里)在最近3場比賽中獲得的總分。

到目前為止,我想出的是:

data["Home_Momentum"] = data.groupby("HomeTeam")["H_Pts"].apply(lambda x: x.rolling(3).sum().shift())

但是,這樣做的問題是它沒有考慮球隊的客場比賽。

您有任何解決方法的想法嗎?

重命名列為多索引。 堆棧並滾動

df.columns = [
    ['Team', 'Team', 'Points', 'Points'],
    ['Home', 'Away', 'Home', 'Away']
]

d1 = df.stack()

mom = d1.groupby('Team').Points.apply(lambda x: x.shift().rolling(3).sum())

d1.assign(Momentum=mom).unstack()

  Points             Team             Momentum     
    Away Home        Away        Home     Away Home
0      0    3      Getafe   Barcelona      NaN  NaN
1      1    1   Barcelona     Levante      NaN  NaN
2      0    3  Las Palmas   Barcelona      NaN  NaN
3      0    3   Barcelona  Las Palmas      7.0  NaN
4      1    1      Madrid   Barcelona      NaN  4.0

我們也可以包括少於3個游戲的總和。

df.columns = [
    ['Team', 'Team', 'Points', 'Points'],
    ['Home', 'Away', 'Home', 'Away']
]

d1 = df.stack()

mom = d1.groupby('Team').Points.apply(lambda x: x.shift().rolling(3, 1).sum())

d1.assign(Momentum=mom).unstack()

  Points             Team             Momentum     
    Away Home        Away        Home     Away Home
0      0    3      Getafe   Barcelona      NaN  NaN
1      1    1   Barcelona     Levante      3.0  NaN
2      0    3  Las Palmas   Barcelona      NaN  4.0
3      0    3   Barcelona  Las Palmas      7.0  0.0
4      1    1      Madrid   Barcelona      NaN  4.0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM