Marcio Mendonça
Marcio Mendonça

Reputation: 25

Adding a new column, in pandas, derived from another

I want to add a new column named 'NormalizedAnnualCompensation' derived from another 2 columns (CompTotal and CompFreq). Here is my code:

for compensation in df['CompFreq']:
  if compensation == 'Yearly':
    df['NormalizeAnnualCompensation'] = df['CompTotal']
  elif compensation == 'Monthly':
    df['NormalizeAnnualCompensation'] = df['CompTotal']* 12.0
  elif compensation == 'Weekly':
    df['NormalizeAnnualCompensation'] = df['CompTotal'] * 52.0

And the output

output

As you can notice, the output isn't correct, because it's simple a straight up copy from the column CompTotal. How can I fix this?

Upvotes: 1

Views: 197

Answers (1)

user2246849
user2246849

Reputation: 4407

You can do it like this:

df['NormalizeAnnualCompensation'] = df['CompTotal'] * df['CompFreq'].map({'Yearly': 1.0, 'Monthly': 12.0, 'Weekly': 52.0})

Upvotes: 1

Related Questions