pandas dataframe column manipulation


I have a dataframe that look like this:

Letter   num  
A        5   
B        4    
A        3  
B        3  

I want to add 3 if letter = A and 2 if letter = B
I tried this:

for i in df:    
  if df['Letter'] == A:  
    df['num'] = df['num'] + 3
    df['num'] = df['num'] + 2

but i get this: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Asked By: Mostafa Waleed



here is one way to do it

# dictionary of the letters and associated values to add
d = {'A' : 3, 'B':2}

# map the letter to get the value and add to the num
df['num']=df['num'] + df['Letter'].map(d)
    Letter  num
0   A   8
1   B   6
2   A   6
3   B   5

Answered By: Naveed
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.