How to use the apply() function for a single column in Pandas?



We can use apply() function on a column of a DataFrame with lambda expression.

Steps

  • Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.

  • Print input DataFrame, df.

  • Override column x with lambda x: x*2 expression using apply() method.

  • Print the modified DataFrame.

Example

 Live Demo

import pandas as pd df = pd.DataFrame(    {       "x": [5, 2, 1, 5],       "y": [4, 10, 5, 10],       "z": [1, 1, 5, 1]    } ) print "Input DataFrame is:
", df df['x'] = df['x'].apply(lambda x: x * 2) print "After applying multiplication of 2 DataFrame is:
", df

Output

Input DataFrame is:    x  y  z 0  5  4  1 1  2 10  1 2  1  5  5 3  5 10  1 After applying multiplication of 2 DataFrame is:     x  y   z 0  10  4   1 1   4 10   1 2   2  5   5 3  10 10   1
Updated on: 2021-08-30T12:15:24+05:30

16K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements