13

Say you have a DataFrame with columns;

 col_1    col_2 
   1        a
   2        b
   3        c
   4        d
   5        e

how would you change the values of col_2 so that, new value = current value + 'new'

1 Answer 1

16

Use +:

df.col_2 = df.col_2 + 'new'
print (df)
   col_1 col_2
0      1  anew
1      2  bnew
2      3  cnew
3      4  dnew
4      5  enew

Thanks hooy for another solution:

df.col_2 += 'new'

Or assign:

df = df.assign(col_2 = df.col_2 + 'new')
print (df)
   col_1 col_2
0      1  anew
1      2  bnew
2      3  cnew
3      4  dnew
4      5  enew
Sign up to request clarification or add additional context in comments.

3 Comments

@jezrael it says that the df has no attribute to assign, and using + doesnt work either. Is there a way to do it through a loop? i.e : for i in df['col2']: .... i+'new'
What is df.info() ? Maybe need alternative with [] like df['col_2'] = df['col_2'] + 'new'
df.col_2 += 'new' worked for me. Don't know why this answer is not accepted?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.