In Pandas, the apply() function is used to apply a function along the axis of a DataFrame or Series. It is a powerful tool for Data Science tasks as it allows you to perform custom operations on the data. You can use apply() with lambda functions or any custom function you define.
Example Code:
import pandas as pd
# Example 1: Applying a lambda function to a Series
data = pd.Series([10, 20, 30, 40])
squared_values = data.apply(lambda x: x**2)
print(squared_values)
# Output:
# 0 100
# 1 400
# 2 900
# 3 1600
# dtype: int64
# Example 2: Applying a custom function to a DataFrame
data = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
def sum_of_columns(row):
return row['A'] + row['B']
data['Sum'] = data.apply(sum_of_columns, axis=1)
print(data)
# Output:
# A B Sum
# 0 1 4 5
# 1 2 5 7
# 2 3 6 9