搜索数据帧中多列的最后一次发生 [英] Search for the last occurence in multiple columns in a dataframe

查看:103
本文介绍了搜索数据帧中多列的最后一次发生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个类似于以下结构的大数据框

Suppose i have a large dataframe similar to the structure below

 home| away|  home_score| away_score
    A|    B|           1|          0
    B|    C|           1|          1
    C|    A|           1|          0

我想找到最后一个分数,无论家庭/家庭。例如,A,B和C组的最后一个分数分别为0,1和1,并返回原始数据框:

I want to find the last score regardless of home / away. For example, last score of team A, B and C are 0, 1 and 1 respectively and fill back to the original dataframe:

 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,但我不知道如何组合回家/离开的结果。

I have tried groupby and shift but I am not sure how to combine the home / away results.

推荐答案

你可以尝试这样的东西。 1)通过向前两列名称添加后缀,使所有列名可以分割; 2)拆分列标题并将其转换为多索引; 3)使用 stack 将表格融化为长格式,由团队分组并获取最新分数:

You can try something as this. 1) make all column names splittable by adding suffix to the first two columns names; 2) split the column headers and transform it to multi index; 3) melt table to long format with stack, group by the teams and get the latest score:

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

To merge it back to the original data frame, you can use 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

这篇关于搜索数据帧中多列的最后一次发生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆