Home > Mobile >  Calculating the average of several numbers and obtaining a penalty
Calculating the average of several numbers and obtaining a penalty

Time:12-28

I have an Excel file like this enter image description here

I want to say that if the average purchase of these people in 3 months was below 60, these people should be fined 120 thousand dollars.

I tried to solve the problem by writing this code

import pandas as pd

file_df = pd.read_excel('users.xlsx')


def penalty_calculation(df):
    sum_of_three_month = df["First month purchase "]   df["Purchase of the second month"]   df["Purchase of the third month"]
    df["Average purchase of 3 months"] = sum_of_three_month // 3
    if df["Average purchase of 3 months"] <= 60:
        df["penalty"] = "$120000"


penalty_calculation(file_df)

But I face this error

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

what is the problem ?

CodePudding user response:

You can use numpy where -

df["penalty"] = np.where(df["Average purchase of 3 months"]<60, "$120000", None)

This will result "$120000" where "Average purchase of 3 months" is less than 60 and None otherwise.

CodePudding user response:

In case you want to do it in a loop

for index, row in df.iterrows():
    if (df.loc[index, 'Average purchase of 3 months'] <= 60):
        df.loc[index, 'Penalty'] = "$120000"
  • Related