0

I am looking for script which will print salary, annualsalary, bonus of an employee. sal is the only column available in DF, and other two columns are expressions which will derive from sal.

annualsalary = 12*sal, bonus=sal*comm/100

i am trying below code

empdf.loc[:,'sal':][['sal'], ['sal']*12, ['sal']*['comm']/100]

can you help me in correcting above code?

Stefan
  • 1,697
  • 15
  • 31

1 Answers1

2

Use temporary calculated fields with assign()

import random
df = pd.DataFrame([{"sal":random.randint(10,15)*100} for i in range(10)])
comm = 20
df.assign(
    annualsalary=lambda dfa: dfa["sal"]*12,
    bonus=lambda dfa: dfa["sal"]*(comm/100)
)

output

  sal  annualsalary  bonus
 1000         12000  200.0
 1400         16800  280.0
 1200         14400  240.0
 1400         16800  280.0
 1500         18000  300.0
 1500         18000  300.0
 1100         13200  220.0
 1300         15600  260.0
 1000         12000  200.0
 1000         12000  200.0
Rob Raymond
  • 29,118
  • 3
  • 14
  • 30
  • 1
    using `lambda` is redundant here, you can just do `df.assign(annualsalary = df['sal']*12, bonus = df['sal']*(comm/100))` – Ch3steR Aug 24 '20 at 06:35
  • 2
    @Ch3steR agreed - however for future maintainability where columns are derived off derived columns, I use pattern of always use `lambda` – Rob Raymond Aug 24 '20 at 06:37