Help with a conditional loop in a dataframe

Hi,can anyone help me? i am trying to fill a column of a dataset using a conditional loop. To do that i am trying to fill a column called “new_amount” with these conditions: if in the same row the “currency” column is “INR”, then “new_amount” should copy the value of "sales_amount ", but if it says “USD” them the value in “new_amount” should be equal to ("sales_amount ")*75. For what i can see the script is doing what i want but is sending a warning that i dont understand.

This is a short version of the dataframe (the original is too big).
sales2.xlsx (6.0 KB)

And this is the link that i should see but i am not seing what i am doing wrong:
https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy

This is the code:

k=0
for valor in sales["currency"]:
    if valor =="INR":
        sales['new_amount'][k]=sales["sales_amount"][k]
    elif valor =="USD":
        sales["new_amount"][k]=(sales["sales_amount"][k])*75
    k+=1```



Thanks! :)

Try something like this:

sales["new_amount"] = sales["sales_amount"]
mask = sales["currency"] == "USD"
sales.loc[mask,"new_amount] = sales.loc[mask,"new_amount]*75

Remember that with data frames you can do vectorized operations.

The error is getting thrown because you are using chained selection:

dataframe___first selection____second selection
sales______['new_amount']____[k]

above I used:
dataframe.loc[mask to select rows, desired cloumn]

1 Like

Thanks a lot! :smile:

1 Like