[英]Search for the last occurence in multiple columns in a dataframe
假設我有一個類似於下面結構的大型數據幀
home| away| home_score| away_score
A| B| 1| 0
B| C| 1| 1
C| A| 1| 0
我想找到最后的分數,無論家里/外。 例如,團隊A,B和C的最后得分分別為0,1和1,並填充回原始數據幀:
home| away| home_score| away_score| last_score_home| last_score_away|
A| B| 1| 0| | |
B| C| 1| 1| 0| |
C| A| 1| 0| 1| 1|
...
我嘗試過groupby和shift,但我不確定如何結合主/結果。
你可以試試這個。 1)通過在前兩列名稱中添加后綴,使所有列名可拆分; 2)拆分列標題並將其轉換為多索引; 3)融合表到長格式與stack
,由團隊分組並獲得最新分數:
df.columns = df.columns.str.replace("^([^_]+)$", "\\1_team").str.split("_", expand=True)
df.stack(level=0).groupby("team").tail(1)
# score team
#1 home 1 B
#2 away 0 A
# home 1 C
更新 :
要將其合並回原始數據框,您可以使用join
:
df.columns = df.columns.str.replace("^([^_]+)$", "\\1_team").str.split("_", expand=True)
df1 = df.stack(level=0).groupby("team").tail(1)
# join the result back to the original transformed data frame
df2 = df.stack(level=0).join(df1.score, rsuffix = "_last").unstack(level=1)
df2.columns = [x + "_" + y for x, y in df2.columns]
df2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.