close

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

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How can I use the apply() function for a single column in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

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

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

    Given a sample dataframe df as:
    a,b 1,2 2,3 3,4 4,5

  2. use the apply() function for a single column

    Given a sample dataframe df as:
    a,b 1,2 2,3 3,4 4,5

Method 1

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

Method 2

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  c
0  15  15  5
1  20  10  7
2  25  30  9



df['a'] = df['a'].map(lambda a: a / 2.)

      a   b  c
0   7.5  15  5
1  10.0  10  7
2  12.5  30  9

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read