Created
December 1, 2016 22:18
-
-
Save MaxHalford/f233d0e5178847a273b357f3fd79a418 to your computer and use it in GitHub Desktop.
Group budget balancing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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