How to apply a function to each element or column of a pandas DataFrame?

Published on Aug. 22, 2023, 12:17 p.m.

To apply a function to each element or column of a pandas DataFrame, you can use the apply() method. Here’s an example of applying a function to each element of a DataFrame:

import pandas as pd

# Define a function to multiply a number by 2
def multiply_by_2(x):
    return x * 2

# Create a DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

# Apply the function to each element of the DataFrame
result = df.applymap(multiply_by_2)

print(result)

This will output:

   A   B
0  2   8
1  4  10
2  6  12

In the example above, we created a DataFrame and applied the multiply_by_2 function to each element of the DataFrame using the applymap() method. This method applies a function to every element of the DataFrame.

To apply a function to each column of a DataFrame, you can use the apply() method. Here’s an example:

import pandas as pd

# Define a function to calculate the sum of a Series
def sum_series(series):
    return series.sum()

# Create a DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

# Apply the function to each column of the DataFrame
result = df.apply(sum_series)

print(result)

This will output:

A     6
B    15
dtype: int64

In the example above, we created a DataFrame and applied the sum_series function to each column of the DataFrame using the apply() method. This method applies a function to every column of the DataFrame.

I hope this helps! Let me know if you have any other questions.

Tags: