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)
CodePudding user response:
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.
CodePudding user response:
You don't need loops here, example:
df = pd.DataFrame(range(10), columns=['my_col'])
coefs = np.array([0.1, 0.3, 0.5])
df.loc[:, ['my_col'] * len(coefs)].mul(coefs)\
.set_axis([f'Bonus Payout {int(coef*100)} %' for coef in coefs],
axis=1)
Bonus Payout 10% Bonus Payout 30% Bonus Payout 50%
0 0.0 0.0 0.0
1 0.1 0.3 0.5
2 0.2 0.6 1.0
3 0.3 0.9 1.5
4 0.4 1.2 2.0
5 0.5 1.5 2.5
6 0.6 1.8 3.0
7 0.7 2.1 3.5
8 0.8 2.4 4.0
9 0.9 2.7 4.5
CodePudding user response:
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)