'creating multiple columns with a loop based on other column in pandas
Hello everyone I have a working code in python but it is written in a crude way because I am still learning the fundamentals and require some insight.
I am creating 40 columns based on one column like i shared a small part of it below:
df["Bonus Payout 80%"]=0
df["Bonus Payout 81%"]=df["Monthly gross salary 100% (LC)"]*0.01
df["Bonus Payout 82%"]=df["Monthly gross salary 100% (LC)"]*0.02
df["Bonus Payout 83%"]=df["Monthly gross salary 100% (LC)"]*0.03
df["Bonus Payout 84%"]=df["Monthly gross salary 100% (LC)"]*0.04
df["Bonus Payout 85%"]=df["Monthly gross salary 100% (LC)"]*0.05
df["Bonus Payout 80%"]=df['Bonus Payout 80%'].apply('{:,.2f}'.format)
df["Bonus Payout 81%"]=df['Bonus Payout 81%'].apply('{:,.2f}'.format)
df["Bonus Payout 82%"]=df["Bonus Payout 82%"].apply('{:,.2f}'.format)
df["Bonus Payout 83%"]=df["Bonus Payout 83%"].apply('{:,.2f}'.format)
df["Bonus Payout 84%"]=df["Bonus Payout 84%"].apply('{:,.2f}'.format)
df["Bonus Payout 85%"]=df["Bonus Payout 85%"].apply('{:,.2f}'.format)
the lines of code goes on until bonus payout 120% how can i tidy this up and convert it to a more coder way?
any help is appreciated
edit : my first lines of code is :
df["Bonus Payout 80%"]=df["Monthly gross salary 100% (LC)"]*0.00
df["Bonus Payout 80%"]=df['Bonus Payout 80%'].apply('{:,.2f}'.format)
and the last one
df["Bonus Payout 120%"]=df["Monthly gross salary 100% (LC)"]*0.40
df["Bonus Payout 120%"]=df['Bonus Payout 120%'].apply('{:,.2f}'.format)
Solution 1:[1]
You can use f-strings and for loops:
j = 0
for i in range(80,121):
df[f"Bonus Payout {i}%"]=df["Monthly gross salary 100% (LC)"]*j
df[f"Bonus Payout {i}%"]=df[f'Bonus Payout {i}%'].apply('{:,.2f}'.format)
j += 0.01
P.S.: I have edited my answer after question edit.
Solution 2:[2]
You can use a for loop for that, in combination with np.arange
for i in np.arange(0,0.4,0.01):
df["Bonus Payout"+str(int(80+i*100))+"%"]=df["Monthly gross salary 100% (LC)"]*i
df["Bonus Payout"+str(int(80+i*100))+"%"]=df["Bonus Payout"+str(int(80+i*100))+"%"].apply('{:,.2f}'.format)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
