lundi 11 mai 2020

Not getting desired statements from dataframe looping

I have a nested dataframe:

df1:
name   date    amount
A     2019      10
B     2019      20
C     2019      30
d     2020      10
e     2020      20

df2:
name   date    amount
f      2019      5
g      2019      10
h      2020      10
i      2020      10
j      2020      5
k      2020      5

And I am currently looping through it and trying to print statements adding the amount of 'amount' by the year and the percentage difference based on if it decreased or increased. DESIRED OUTPUT:

Df1: DECREASED -  pre_count: 60  now count: 30 difference: -50%
Df2: INCREASED -  pre count: 15  now count: 30 difference: 100%

This is what I have:

def percentage():
amountlist = []
pre_count = 0
now_count = 0
pre_date = 2019
now_date = 2020
for name, df in dfnest_dict.items():
    for index, row in df.iterrows():
        if row['date'] == pre_date:
            pre_count += row['amount']
        elif row['date'] == new_update:
            new_count += row['amount']
    x = pre_amount_count
    y = now_amount_count
    math = int(((x - y)*100) / y)
    if(y>x):
        msgone =  str("{}: INCREASED PRE COUNT: {} NOW COUNT {} DIFFERENCE {}%".format(name, x, y, math))
        amountlist.append(msgone)
        inc_str = str("\n".join(amountlist))
        return devicelist, inc_str
    elif(y < x):
        mstwo =  str("{}: DECREASED PRE COUNT: {} NOW COUNT {} DIFFERENCE {}%".format(name, x, y, math))
        amountlist.append(mstwo)
        dec_str = str("\n".join(amountlist))
        return devicelist, dec_str

When I call the function with:

one, two = percentage()

and print them I only get one output and sometimes its the wrong message. I'll get the decreasing message instead of increasing etc

any ideas?

Aucun commentaire:

Enregistrer un commentaire