May-24-2019, 10:55 PM
I know it's ugly and I'm not experienced with pandas but it works:p
import pandas as pd def get_team_names(df): return df[0][0], df[1][0] df = pd.DataFrame([ ["Gothenburg", "Malmo", 2018,"A"], ["Malmo","Gothenburg", 2018, "D"], ["Malmo", "Gothenburg", 2018, "A"], ["Gothenburg", "Malmo", 2018, "H"], ["Gothenburg", "Malmo" ,2018, "D"], ["Gothenburg", "Malmo", 2018, "A"], ["Gothenburg", "Malmo", 2018, "H"], ["Malmo", "Gothenburg", 2018, "A"], ["Gothenburg", "Malmo", 2018, "H"], ["Malmo", "Gothenburg", 2018, "H"], [ "Malmo","Gothenburg", 2018, "D"], [ "Malmo", "Gothenburg",2018, "H"], ]) team_1, team_2 = get_team_names(df) df.columns = ['H_team', 'A_team', 'Year', 'Result'] draws = df['Result']=='D' hh = (df['Result']=='H').where(df['H_team'] == team_1) * 3 ha = (df['Result']=='A').where(df['A_team'] == team_1) * 3 ah = (df['Result']=='H').where(df['H_team'] == team_2) * 3 aa = (df['Result']=='A').where(df['A_team'] == team_2) * 3 team_1_points = hh.add(ha, fill_value=0).add(draws, fill_value=0).cumsum().shift(1) team_2_points = ah.add(aa, fill_value=0).add(draws, fill_value=0).cumsum().shift(1) df['H_points'] = team_1_points.where(df['H_team'] == team_1, team_2_points) df['A_points'] = team_1_points.where(df['A_team'] == team_1, team_2_points) print(df)
Output: H_team A_team Year Result H_points A_points
0 Gothenburg Malmo 2018 A NaN NaN
1 Malmo Gothenburg 2018 D 3.0 0.0
2 Malmo Gothenburg 2018 A 4.0 1.0
3 Gothenburg Malmo 2018 H 4.0 4.0
4 Gothenburg Malmo 2018 D 7.0 4.0
5 Gothenburg Malmo 2018 A 8.0 5.0
6 Gothenburg Malmo 2018 H 8.0 8.0
7 Malmo Gothenburg 2018 A 8.0 11.0
8 Gothenburg Malmo 2018 H 14.0 8.0
9 Malmo Gothenburg 2018 H 8.0 17.0
10 Malmo Gothenburg 2018 D 11.0 17.0
11 Malmo Gothenburg 2018 H 12.0 18.0