tax calculation python pandas calculate the tax according to the given scenario and add to a new column

Use map:

country_tax = {'India': 0, 'USA': 3, 'China': 4}
product_tax = {'laptop': 2, 'mobile': 3}

df['final_price'] = df['price'] + (df['country'].map(country_tax) * df['price'] 
                    + df['product'].map(product_tax) * df['price']) / 100
print(df)

# Output
  country product  quantity  price  final_price
0   India  laptop        50  30000      30600.0
1     USA  laptop        50  30000      31500.0
2   China  laptop       100  30000      31800.0
3   India  mobile        50  10000      10300.0
4     USA  mobile        50  10000      10600.0
5   China  mobile       100  10000      10700.0

Update

Is there any chance of using lambda function for this

Less efficient but lambda:

get_final_price = lambda x: x['price'] + (x['price'] * country_tax[x['country']] 
                            + x['price'] * product_tax[x['product']]) / 100

df['final_price'] = df.apply(get_final_price, axis=1)
print(df)

# Output
  country product  quantity  price  final_price
0   India  laptop        50  30000      30600.0
1     USA  laptop        50  30000      31500.0
2   China  laptop       100  30000      31800.0
3   India  mobile        50  10000      10300.0
4     USA  mobile        50  10000      10600.0
5   China  mobile       100  10000      10700.0

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top