Home > Software design >  python pandas tax calculation: calculate the tax according to the given senario and add it to a new
python pandas tax calculation: calculate the tax according to the given senario and add it to a new

Time:01-03

country  product quantity   price              final_price
India     laptop  50        30000             
USA       laptop  50        30000
China     laptop  100       30000
India     mobile  50        10000
USA       mobile  50        10000
China     mobile  100       10000

country_tax = {"india":0%,"usa":3%,"china":4%}
product_tax = {"laptop":2%,"mobile":3%}

final price is the new column where the calculated tax should be appended can anyone suggest me a good way to do this by using lambda

Thanks

CodePudding user response:

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

CodePudding user response:

You can use map:

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

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

The same result can be obtained using a lambda function:

df['final_price'] = (1   (df['country'].apply(lambda x: country_tax[x])   df['product'].apply(lambda x: product_tax[x])) / 100) * df['price'] 

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
  • Related