I have a situation. Let me say that I have the following example dataframe loans:
test_df = pd.DataFrame({'name': ['Jack','Jill','John','Jack','Jill'],
'date': ['2016-08-08','2016-08-08','2016-08-07','2016-08-08','2016-08-08'],
'amount': [1000.0,1500.0,2000.0,2000.0,3000.0],
'return_amount': [5000.0,2000.0,3000.0,0.0,0.0],
'return_date': ['2017-08-08','2017-08-08','2017-08-07','','2017-08-08']})
test_df.head()
amount date name return_amount return_date
0 1000.0 2016-08-08 Jack 5000.0 2017-08-08
1 1500.0 2016-08-08 Jill 2000.0 2017-08-08
2 2000.0 2016-08-07 John 3000.0 2017-08-07
3 2500.0 2016-08-08 Jack 0.0
4 2500.0 2016-08-08 Jill 0.0 2017-08-08
There are several operations that I need to perform after grouping this frame by name (grouping loans per person):
1) return amountmust be distributed in proportion to the amount amount.
2) If there return dateis ANY for a given person for a loan , then all return_dates should be converted to empty lines. ''
I already have a function that I use to distribute the proportional amount of the return:
def allocate_return_amount(group):
loan_amount = group['amount']
return_amount = group['return_amount']
sum_amount = loan_amount.sum()
sum_return_amount = return_amount.sum()
group['allocated_return_amount'] = (loan_amount/sum_amount) * sum_return_amount
return group
And I use grouped_test_df = grouped_test_df.apply(allocate_return_amount)to apply it.
, , - , , , - return_date, , return_dates '..
GroupBy.all pandas , , , - ?
, :
ideal_test_df.head()
amount date name return_amount return_date
0 1000.0 2016-08-08 Jack 0.0 ''
1 1500.0 2016-08-08 Jill 666.66 2017-08-08
2 2000.0 2016-08-07 John 3000.0 2017-08-07
3 2500.0 2016-08-08 Jack 0.0 ''
4 2500.0 2016-08-08 Jill 1333.33 2017-08-08
, pandas, , !