Pandas apply custom function

Pandas apply() function is used to apply a custom function to each element of a DataFrame or Series. It’s a versatile function that allows you to perform operations on one or more columns and return the results. Here’s an example to demonstrate its usage:

import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
  
def square(x):
    return x ** 2

df['A_squared'] = df['A'].apply(square)
print(df)

In the above code, we create a DataFrame with two columns ‘A’ and ‘B’. We define a custom function ‘square’ that squares a given value. Using the apply() function, we apply this function to each element of the ‘A’ column and store the results in a new column ‘A_squared’. Finally, we print the updated DataFrame.

The apply() function also works with Series. Here’s an example:

import pandas as pd
s = pd.Series([1, 2, 3])
  
def square(x):
    return x ** 2

s_squared = s.apply(square)
print(s_squared)

In this example, we define a Series ‘s’ and a custom function ‘square’. We use the apply() function to apply the ‘square’ function to each element of the Series and store the results in a new Series ‘s_squared’. Finally, we print the updated Series.

Overall, the apply() function is a powerful tool in pandas that allows you to apply custom functions element-wise to DataFrames and Series. It enables flexible data manipulation and transformation based on your specific requirements.

Leave a comment