'park_id', 'hr', 'triple', 'double', 'single', 'hits'] COLUMNS_AWAY = ['away_team_id', 'hr', 'triple', 'double', 'single', 'hits'] for team in df_event2018['home_team_id'].unique(): home_stadium = parks[team] _df_home = df_event2018.query(f'home_team_id == "{team}" and park_id == "{home_stadium}"') home_games = len(_df_home['game_id'].unique()) _df_home = _df_home[COLUMNS_HOME].groupby(['home_team_id', 'park_id'], as_index=False)[COLUMNS_HOME].sum() _df_away = df_event2018.query(f'away_team_id == "{team}"') away_games = len(_df_away['game_id'].unique()) _df_away = _df_away[COLUMNS_AWAY].groupby(['away_team_id'], as_index=False)[COLUMNS_AWAY].sum() teams.append({ 'park_id': home_stadium, 'team': team, 'home_games': home_games, 'home_hr': _df_home['hr'][0], 'home_triple': _df_home['triple'][0], 'home_double': _df_home['double'][0], 'home_single': _df_home['single'][0], 'home_hits': _df_home['hits'][0], 'away_games': away_games, 'away_hr': _df_away['hr'][0], 'away_triple': _df_away['triple'][0], 'away_double': _df_away['double'][0], 'away_single': _df_away['single'][0], 'away_hits': _df_away['hits'][0], }) df_pf = pd.DataFrame(teams)