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

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


Given a sample dataframe df as:

a,b1,22,33,44,5

what you want is:

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

that returns:

   a  b0  2  21  3  32  4  43  5  5


For a single column better to use map(), like this:

df = pd.DataFrame([{'a': 15, 'b': 15, 'c': 5}, {'a': 20, 'b': 10, 'c': 7}, {'a': 25, 'b': 30, 'c': 9}])    a   b  c0  15  15  51  20  10  72  25  30  9df['a'] = df['a'].map(lambda a: a / 2.)      a   b  c0   7.5  15  51  10.0  10  72  12.5  30  9


You don't need a function at all. You can work on a whole column directly.

Example data:

>>> df = pd.DataFrame({'a': [100, 1000], 'b': [200, 2000], 'c': [300, 3000]})>>> df      a     b     c0   100   200   3001  1000  2000  3000

Half all the values in column a:

>>> df.a = df.a / 2>>> df     a     b     c0   50   200   3001  500  2000  3000


matomo