Home > Software design >  How to create summary in list and create total in python
How to create summary in list and create total in python

Time:01-11

The code below is working but I need help in summarizing and sorting the output to create a more readable output.

account = []
amount = []

pmtReceived = []
for payment in payments_received: 
    print ("  ({:>15}) <-  {}".format(payment['amount'] ,payment['from']))
    pmtReceived.append(payment['amount'])

    account.append(payment['to'])
    amount.append(payment['amount'])

    df = pd.DataFrame(list(zip(lst1, lst2)), columns =['To', 'Amount'])

print (df)

Current Output:

       Account      Amount       
0  BD001ABC... 180.0000000 
1  ACC011XY... 120.0000000
2  ACC011XY... 444.0000000  
3  012ABC1A... 190.0000000
4  012ABC1A...  50.0000000
5  012ABC1A... 110.0000000
6  012ABC1A... 400.0000000  
7  XY123AYT...   0.4900000

Needed Output:

BD001ABC (1 Transaction / 180.0)
ACC011XY (2 Transaction / 564.0)
012ABC1A (4 Transaction / 750.0)
XY123AYT (1 Transaction / 0.49)

CodePudding user response:

try

payments_received.sort()

then run your loop. if you need descending order try payments_received.sort(reverse=True)

cheers

CodePudding user response:

Is this what you are looking for?

Add this to your current function and return result

result = df1.groupby('Account')['Amount'].agg(['count','sum']).reset_index()
result['count'] = result['count'].astype(str)   ' Transactions'
print(result)
       Account           count     sum
0  012ABC1A...  4 Transactions  750.00
1  ACC011XY...  2 Transactions  564.00
2  BD001ABC...  1 Transactions  180.00
3  XY123AYT...  1 Transactions    0.49

If you want to also display the list of all the transactions, then you can add one more aggregation method to the .agg() -

df.groupby('Account')['Amount'].agg([list,'count','sum']).reset_index()
       Account                         list  count     sum
0  012ABC1A...  [190.0, 50.0, 110.0, 400.0]      4  750.00
1  ACC011XY...               [120.0, 444.0]      2  564.00
2  BD001ABC...                      [180.0]      1  180.00
3  XY123AYT...                       [0.49]      1    0.49

References for further reading

Here is the official documentation on pandas.groupby and here is a blog / tutorial that should be an end-to-end guide for how to use groupby in pandas. Disclaimer, the author of the blog is me.

  • Related