簡體   English   中英

獲取 pandas dataframe 中的最新值

[英]fetching most recent values in pandas dataframe

這是我的 pandas dataframe 的樣本

Player_A    Player_B    Gain_A    Gain_B
  John         Max        -3        3
  Max          Lucy        4       -4
  Lucy         John        1       -1
  Max          John       -5        5
  John         Lucy       -2        2

我希望創建一個新列“Sum_2_A”,它顯示玩家“增益”的最近兩個實例的總和(不包括當前行的值)

即,給定樣本中的預期 output 如下

Player_A    Player_B    Gain_A    Gain_B    Sum_2_A    
  John         Max        -3        3         -3       
  Max          Lucy        4       -4          4      
  Lucy         John        1       -1          1       
  Max          John       -5        5          7         
  John         Lucy       -2        2          4         

我可以通過 for 循環來做到這一點,但它太慢了,無法使用。 任何幫助表示贊賞。

謝謝

IIUC,您可以將數據轉換為長格式,在 groupby 上滾動總和:

new_df = (pd.wide_to_long(df.reset_index(), stubnames=['Player','Gain'], 
                i='index',j='type',
                sep='_', suffix = '.*'
               )
            .sort_index()
         )

new_df['Sum_2'] = (new_df.groupby('Player')
                         .Gain.rolling(3).sum()
                         .reset_index('Player',drop=True)
                         .sort_index()
                         .sub(new_df['Gain'])
                         .fillna(new_df['Gain'])
                  )

new_df.unstack('type')

Output:

      Player       Gain    Sum_2     
type       A     B    A  B     A    B
index                                
0       John   Max   -3  3  -3.0  3.0
1        Max  Lucy    4 -4   4.0 -4.0
2       Lucy  John    1 -1   1.0 -1.0
3        Max  John   -5  5   7.0 -4.0
4       John  Lucy   -2  2   4.0 -3.0

暫無
暫無

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

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