Pandas - 对每隔一行应用函数

6
我有一个数据框,我想做的是在同一位置上列出获胜和失败队伍的得分。我尝试使用lambda函数,但没有成功。我当前拥有的数据框是第一个,我想创建一个形式为第二个问题的数据集。谢谢。

enter image description here

an

GameId      Team    Home    Score
1           Spirit  1       81
1           Rockers 0       66
2           Lightning   1   73
2           Flames  0       82


Game ID Home Team   Away Team   Home Score  Away Score
1       Spirit      Rockers     81          66
2       Lightning   Flames      73          82
3个回答

4

试试这个:

输入:

import pandas as pd

raw_df = pd.DataFrame({"GameId": [1, 1, 2, 2],
                       "Team": ["Spirit", "Rockets", "Lighting", "Flames"],
                       "Home": [1, 0, 1, 0],
                       "Score": [81, 66, 73, 82]})
print(raw_df)

输出:

   GameId      Team  Home  Score
0       1    Spirit     1     81
1       1   Rockets     0     66
2       2  Lighting     1     73
3       2    Flames     0     82

输入:

raw_df.loc[:, "Home"] = raw_df.Home.map({
        1: "Home",
        0: "Away"
    })

result = raw_df.pivot_table(index=["GameId"],
                            columns=["Home"],
                            values=["Team", "Score"],
                            aggfunc={"Team": lambda team: " ".join(team.tolist()),
                                     "Score": lambda score: score})

result = result.sort_index(axis="columns", level=[0, "Home"], ascending=False)
result.columns = [' '.join(reversed(col)) for col in result.columns]
print(result)

输出:

       Home Team Away Team  Home Score  Away Score
GameId                                            
1         Spirit   Rockets          81          66
2       Lighting    Flames          73          82

1
我进行了一次1000000行的测试。当前实现花费了119ms,使用.map只需44ms。1. maps = {0:'Away',1:'Home'} 2. raw_df.Home = raw_df.Home.map(maps)。两种方式都足够快。我个人认为.map看起来更清晰,特别是对于更多的映射。不管怎样,非常好的答案+10。 - Trenton McKinney
1
哈哈。我只是想告诉你,我也做了同样的事情。你是对的,使用 Map 更加简洁。 - Xu Qiushi
1
再见! - Trenton McKinney
1
再见。\握手 - Xu Qiushi

2
import pandas as pd
df=pd.DataFrame({'GameId':[1,1,2,2],'Team': ['Spirit','Rockers','Lighting','Flames'],'Home':[1,0,1,0],'Score':[81,66,73,82]})
merge=pd.merge(df,df,left_on='GameId',right_on='GameId')
merge=merge[merge['Home_x']!=merge['Home_y']]
merge=merge.drop_duplicates(subset=['GameId'])
merge=merge[['GameId','Team_x','Team_y','Score_x','Score_y']]
merge.columns=['GameId','Home Team','Away Team','Home Score','Away Score']

enter image description here

解释:使用pd.merge()函数进行自连接。然后,删除在home和away列中具有相同队名的行。之后,在gameId上去重,接着选择所需的列并将它们重命名。


2

首先使用.pivot,然后进行一些列表推导来将列名从元组重命名为所需的名称(由于在枢轴时将Home设置为列,因此列是元组)。 [::-1]在列表推导中连接元组时将名称从例如Team Home反转为Home Team。

df = pd.pivot(df, columns='Home', values=['Team','Score'], index='GameId').reset_index()
df.columns = [' '.join(str(s).strip().replace('1', 'Home').replace('0', 'Away') for s in col[::-1]) for col in df.columns]

输出:

    GameId  Away Team   Home Team   Away Score  Home Score
0   1       Rockers     Spirit      66          81
1   2       Flames      Lightning   82          73

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接