1

I have a dataframe which is grouped and aggregated

df_subsegment:
    segment         Sales   Income  Rent
0   A               184.37  224.24  5242.9  
1   B               45.42   176.79  6693.0  
<+100 rows>

I have created a list from the above dataframe:

    SubSegment_list = df_subsegment['segment'].unique()
    SubSegment_list

[out] array(['A', 'B'], dtype=object)


for i in SubSegment_list:
    var1 = df['Sales']
    var2 = df['Income']
    var3 = df['Rent']
    flag1 = 'up' if var1>0 else 'down'
    flag2 = 'up' if var2>0 else 'down'
    flag3 = 'leverage' if var3>0 else 'deleverage'
    print(f"{SubSegment_list[0]} Sales {flag1} {round(var1)} % vs LY while Total income {flag2} {var2}% vs LY creating {flag3}")

Lets consider that right now the list mentioned above has 2 values only, A and B. then the output gerenated out of this for loop contains two statements but both of them has same values as follows:

A Sales up 184 % vs LY while Total income up 224.24% vs LY creating leverage
A Sales up 184 % vs LY while Total income up 224.24% vs LY creating leverage

How can i generate two unique statements considering the data of each row as follows:

Expected output:

A Sales up 184% vs LY while Total income up 224.24% vs LY creating leverage
B Sales up 45% vs LY while Total income up 176.79% vs LY creating leverage
0

1 Answer 1

3

You can use iterrows:

for _, value in df.iterrows():

    var1 = value['Sales']
    var2 = value['Income']

    seg1 = value['segment']

    flag1 = 'up' if var1>0 else 'down'
    flag2 = 'up' if var2>0 else 'down'

    print(f"{seg1} Sales {flag1} {var1}% vs LY while Total income {flag2} {var2}% vs LY creating leverage")

A Sales up 184.37% vs LY while Total income up 224.24% vs LY creating leverage
B Sales up 45.42% vs LY while Total income up 176.79% vs LY creating leverage
Sign up to request clarification or add additional context in comments.

2 Comments

Could you explain the syntax or logic for the for statement please?
iterrows functions returns index, row information, check the documentation, I replaced indexed with _ since we dont need to use it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.