This is going to require a bit of an explanation. So I am trying to assign records in a dataframe into even groups, but there are constraints on which groups they can be in. There are over 1000 records, so while its not too many rows, I want to write some code to quicken the process as it's going to be repeated. Here's a couple rows with some random cat info to give you a better feel for what I'm trying to do: id pattern size origin Group 1 Spots Beefy Denmark 2 N/A Tiny Sweden 3 Stripes Normal US 4 N/A Normal US 5 Spots Normal Germany 6 Hearts Bowling Ball US Here are the pattern rules that need to be followed (most important): Spots can only be in Group 5 Hearts split between 2 and 4 as even as possible Stripes split between 1 and 3 as even as possible N/A spread across all 5 groups Other rules: Non-US cats split across the 5 groups Evenly distribute Germany across 5 groups Group smaller countries (that have <10 cats in this df) in a single group Good representation of size across groups (this rule is less important than the others) I'm trying to figure out the best way to approach this and I know that all rules can't be followed for my data but I wanted to code for the most optimal grouping possible. Let me know if you need more information or if this wasn't clear enough! Continue reading...