Mostafa Waleed
Mostafa Waleed

Reputation: 11

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
  else:  
    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().

Upvotes: 0

Views: 41

Answers (1)

Naveed
Naveed

Reputation: 11650

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)
df
    Letter  num
0   A   8
1   B   6
2   A   6
3   B   5

Upvotes: 3

Related Questions