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

PandasServer Side ProgrammingProgramming

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:\n", df
df['x'] = df['x'].apply(lambda x: x * 2)
print "After applying multiplication of 2 DataFrame is:\n", 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
raja
Updated on 30-Aug-2021 12:15:24

Advertisements