How can I use the apply() function for a single column?

Amani picture Amani · Jan 23, 2016 · Viewed 373.9k times · Source

I have a pandas data frame with two columns. I need to change the values of the first column without affecting the second one and get back the whole data frame with just first column values changed. How can I do that using apply in pandas?

Answer

Fabio Lamanna picture Fabio Lamanna · Jan 23, 2016

Given a sample dataframe df as:

a,b
1,2
2,3
3,4
4,5

what you want is:

df['a'] = df['a'].apply(lambda x: x + 1)

that returns:

   a  b
0  2  2
1  3  3
2  4  4
3  5  5