Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading