Skip to content

Instantly share code, notes, and snippets.

@MaxHalford
Created December 1, 2016 22:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MaxHalford/f233d0e5178847a273b357f3fd79a418 to your computer and use it in GitHub Desktop.
Save MaxHalford/f233d0e5178847a273b357f3fd79a418 to your computer and use it in GitHub Desktop.
Group budget balancing
import pandas as pd
# Choose the file to balance
csvFile = 'example'
# Clear the log
open('log', 'w').close()
# Open the csv file
df = pd.read_csv('data/{0}.csv'.format(csvFile))
# Obtain sum of amount paid
sums = df.groupby('person').sum()
# Compute the mean total amount
mean = sums['amount'].mean()
# Compute the differences
differences = sums - mean
# Now let's find the steps to balance everything out
while sum(abs(differences['amount'])) != 0:
receiver = differences['amount'].argmax()
giver = differences['amount'].argmin()
amount = min(differences.loc[receiver]['amount'],
abs(differences.loc[giver]['amount']))
# Record the transaction in a file
with open('log', 'a') as log:
log.write(str(giver) +' => '+str(amount)+' => '+str(receiver)+'\n')
# Modify the data
differences.loc[receiver] -= amount
differences.loc[giver] += amount
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment