Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add string to all values in a column of pandas DataFrame

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'

like image 818
mystery man Avatar asked Feb 16 '17 12:02

mystery man


People also ask

How do I add a string to a column in a DataFrame?

By use + operator simply you can concatenate two or multiple text/string columns in pandas DataFrame. Note that when you apply + operator on numeric columns it actually does addition instead of concatenation.

How do I add all values in a column in a DataFrame?

sum() function is used to return the sum of the values for the requested axis by the user. If the input value is an index axis, then it will add all the values in a column and works same for all the columns. It returns a series that contains the sum of all the values in each column.

How do I add a character to a column in pandas?

Append a character or string to start of the column in pandas: Appending the character or string to start of the column in pandas is done with “+” operator as shown below.

How do I add all the values in a column in Python?

sum() function return the sum of the values for the requested axis. If the input is index axis then it adds all the values in a column and repeats the same for all the columns and returns a series containing the sum of all the values in each column.


1 Answers

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
like image 125
jezrael Avatar answered Oct 12 '22 07:10

jezrael