0

I was wondering if someone would be able to help me with the following. I have this dataframe:

df = {'Price': [60.50,5.20,7,20.16,73.50,12.55,8.70,6,54.10,89.40,12,55.50,6,120,13.20], 
      'Discount': [1,1,1,0.5,0.4,1,0.3,0.2,1,1,1,1,1,0.1,0.9]}
df = pd.DataFrame(data=df)

What I am trying to do is iterate through each row in the df and if the Discount amount is 1, then populate the Amount off for that row with 0. Otherwise, it would calculate the amount it has been taken off according to the discount. I have the following code to do this:

for index, row in df.iterrows():
    if row['Discount'] == 1:
        df['Amount off'] = 0
    else:
        df['Amount off'] = df['Price']*df['Discount']

However, once I run it, it does not produce the correct amount off when the discount is 1. Is anyone able to give me some hints and directions on where I am going wrong please?

Thank you in advance!

1
  • 1
    The data doesn't make much sense; if discount meant the same thing across all values, no discount would be 0 and not 1 meaning you could just calculate df['Amount off']=df['Price']*df['Discount'] Commented Aug 1, 2022 at 10:53

1 Answer 1

2

Your mistake is, that you are manipulationg the full dataframe when calling e.g.

df['Amount off'] = 0

Thus after executing this line the total column is 0. Dependent on the last row you will end up with either only 0 or df['Price']*df['Discount']

You can use:

df['Amount off']=df['Price']*df['Discount']
df.loc[df['Discount']==1, 'Amount off']=0
df.head()

First, I calculate the full column and then only change the values where df['Discount']==1

Sign up to request clarification or add additional context in comments.

1 Comment

You could do that in one line: df['Amount off'] = (df['Price'] * df['Discount']).where(df['Discount'].ne(1), 0)

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.