Pandas。在改变其他细胞

2024-04-19 18:34:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在遍历一个包含篮球逐场数据(称为plays_df)的Pandas数据框,并试图从中提取阵容——基本上我有一个在场球员的列表,当我看到他们分入(分出)时,我试图添加(删除)一名球员——但出于某种原因,当我在最后打印数据框时,每个比赛都包含那场比赛最后一场比赛的阵容。我尝试过使用多种形式的列表理解、字典,并以多种不同的方式操纵原始数据帧,最终我总是遇到这个问题。代码在下面,正如你所看到的,我把当前的打印出来,然后把当前的打印回家,当我这样做的时候,它总是正确的,没有这个问题,这就是为什么我对它如此困惑的原因。我该如何解决这个问题

plays_df["AwayOn"] = [[] for i in range(len(plays_df.index))]
plays_df["HomeOn"] = [[] for i in range(len(plays_df.index))]
previous_game_link = ""
for index, row in plays_df.iterrows():
    current_away = []
    current_home = []
    game_link = row["GameLink"]
    if game_link != previous_game_link: #if first play of new game, get starters
        player_indices = player_stat_df.index[player_stat_df["GameLink"] == game_link].tolist()
        players_in_game = player_stat_df.ix[player_indices]
        starter_indices = players_in_game.index[players_in_game["GS"] == 1].tolist()
        starters = players_in_game.ix[starter_indices]
        away_starter_indices = starters.index[starters["Location"] == "A"].tolist()
        away_starters = starters.ix[away_starter_indices]
        home_starter_indices = starters.index[starters["Location"] == "H"].tolist()
        home_starters = starters.ix[home_starter_indices]
        current_away = away_starters["Player"].tolist()
        current_home = home_starters["Player"].tolist()
    else: #middle of game
        current_away = away_last_play
        current_home = home_last_play
        if row["Action"] == "goestothebench": #player subbing out
            if row["H/A"] == "A" and row["Name"] in current_away:                    
                current_away.remove(row["Name"])
            elif row["Name"] in current_home:
                        current_home.remove(row["Name"])
        elif row["Action"] == "entersthegame": #player subbing in
            if row["H/A"] == "A" and row["Name"] not in current_away:
                current_away.append(row["Name"])
            elif row["Name"] not in current_home:
                current_home.append(row["Name"])
    print current_away
    print current_home
    plays_df.at[index, "AwayOn"] = current_away
    plays_df.at[index, "HomeOn"] = current_home
    away_last_play = current_away
    home_last_play = current_home
    previous_game_link = game_link

Tags: nameingamedfhomeindexlinkcurrent