Python Pandas DataFrame: Apply function to all columns

Learn, how can we apply function to all columns on a Python pandas dataframe? By Pranit Sharma Last updated : September 29, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Problem statement

Suppose we have a DataFrame with multiple values containing different integer values (both positive and negative). We need to apply a function to all columns and we will check if a value is greater than 0 then we will return it.

Applying function to all columns

Whenever we want to perform some operation on the entire DataFrame, we use apply() method. The apply() method passes the columns of each group in the form of a DataFrame inside the function which is described in apply() method.

The function which is described inside the apply() method returns a series or DataFrame (NumPy array or even a list).

Let us understand with the help of an example,

Python program to apply function to all columns on a pandas dataframe

# Importing pandas package
import pandas as pd

# Creating two dictionaries
d1 = {

# Creating DataFrame
df = pd.DataFrame(d1)

# Display the DataFrame
print("Original DataFrame:\n",df,"\n\n")

# Using apply method
res = df.applymap(lambda x: x>1)

# Display Result


The output of the above program is:

Example: Apply function to all columns

Python Pandas Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.