2017-02-27 37 views
4

假设我有以下搜索多个列的最后一次出现在数据帧

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和转变,但我不知道如何将家庭结合/离开结果。

回答

4

你可以尝试这样的事情。 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 

enter image description here

+2

不错的作品首先改造索引 –

+0

@RomanPekar感谢您的评论! – Psidom

+0

感谢您的评论!它运作良好,但我需要回填原始数据框。对不起,错误地指出了这个问题。 – Andy

相关问题