Search code examples
pythonpandasdata-analysis

Python - select row cell based on another cell condition


I am writing some python to draw a pie chart. I am attempting to find how many goals were scored using a certain formation. The format of each row is:

date        home_team      away_team home_score away_score  home_formation  away_formation
14/06/2018  Russia      Saudi Arabia         5           0         4-2-3-1         4-1-4-1

What I would like to do it say if the home team has the formation 4-2-3-1, add the home_score to the counter. At the end I will display these goals into a pie chart

for x in df:
if df.home_formation == '4-1-4-1':
    counter += df.home_score

formationScore1 = counter 

My question: How do I go through a CSV file, check if the formation is that one I want and add that rows score to the variable


Solution

  • formations = ['4-1-4-1', '4-2-3-1']  #Add as many as you'd like
    
    formation_scores = {formation: df[df['home_formation'] == formation]['home_score'].sum() for formation in formations}