Creating teams of 12 with equal number of men and women and equal number of managers vs individuals

  Kiến thức lập trình

I have a large csv file that include name, gender, region, and role (manager or Individual). I am attempting to make a script that would read the csv file and sort them into teams of 12 with an equal number of men and women and equal number of managers and individual. Everyone in each team should be from the same region as well.

Here is my code:

import pandas as pd
from collections import defaultdict

def create_teams(df):
    # Group people by region, gender, and role
    regions = defaultdict(lambda: {'M': {'manager': [], 'individual': []}, 'F': {'manager': [], 'individual': []}})
    for _, row in df.iterrows():
        regions[row['region']][row['gender']][row['role']].append(row.to_dict())

    teams = []
    for region, genders in regions.items():
        males_managers = genders['M']['manager']
        males_individuals = genders['M']['individual']
        females_managers = genders['F']['manager']
        females_individuals = genders['F']['individual']
       
        # Calculate the number of teams needed
        num_teams = max(len(males_managers), len(males_individuals), len(females_managers), len(females_individuals)) // 12

        # Distribute members into teams
        for i in range(num_teams):
            team = (males_managers[i*3:(i+1)*3] + males_individuals[i*3:(i+1)*3] + females_managers[i*3:(i+1)*3] + females_individuals[i*3:(i+1)*3])
            teams.append(team)
            

    return teams

# Read data from CSV using pandas
try:
    df = pd.read_csv('name.csv')
    if not isinstance(df, pd.DataFrame):
        raise ValueError("The CSV file did not load into a DataFrame.")
except Exception as e:
    print(f"Error reading the CSV file: {e}")
    exit()

# Create teams
teams = create_teams(df)

# Print teams
for i, team in enumerate(teams):
    print(f"Team {i+1}:")
    for member in team:
        print(f"  {member['name']} ({member['gender']}, {member['region']}, {member['role']})")

This is the current output I have.

Team 1:

Bob (M, North, manager)
Frank (M, North, manager)
Leo (M, North, manager)

The desired output would look like this

Team 1:

Bob (M, North, manager)
Frank (M, North, manager)
Leo (M, North, manager)
Dave (M, North, individual)
Hank (M, North, individual)
Jack (M, North, individual)
Alice (F, North, manager)
Eve (F, North, manager)
Ivy (F, North, manager)
Carol (F, North, individual)
Grace (F, North, individual)
Kathy (F, North, individual)

Team 2:

 Bob (M, North, manager)
 Frank (M, North, manager)
 Leo (M, North, manager)
 Dave (M, North, individual)
 Hank (M, North, individual)
 Jack (M, North, individual)
 Alice (F, North, manager)
 Eve (F, North, manager)
 Ivy (F, North, manager)
 Carol (F, North, individual)
 Grace (F, North, individual)
 Kathy (F, North, individual)

New contributor

Ali is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

4

LEAVE A COMMENT