Chapter 23 Applying Functions
Using apply in NumPy and Pandas is a common practice to perform element-wise operations or to apply custom functions across data structures.
Here are some examples:
23.0.1 Using apply in Pandas:
Pandas’ apply function is very powerful for applying custom functions along either axis (rows or columns) of a DataFrame or across a Series.
23.0.1.1 Applying a Function to a DataFrame Column
Imagine you have a DataFrame df with a column salary, and you want to calculate a 10% increase for all salaries.
23.0.1.2 Applying a Function Across Rows
You have a DataFrame with columns x and y, and you want to create a new column z which is the sum of x and y.
23.0.2 Using apply in NumPy:
NumPy’s apply_along_axis function is used to apply a function along a particular axis of a NumPy array.
23.0.2.1 Applying a Function to Each Row of a 2D NumPy Array
Suppose you have a 2D array and want to calculate the sum of each row.
23.0.3 Key Points to Mention in an Interview:
Pandas’
applyfunction is very versatile and is generally used to apply custom functions row-wise or column-wise in a DataFrame or to a Series.NumPy’s
apply_along_axisis more specific and used for applying a function along a specific axis (rows or columns) of an array.These functions are particularly useful when built-in functions are not sufficient or when custom operations are needed.
While
applycan be convenient, it’s worth mentioning that it can be slower than vectorized operations in Pandas and NumPy, so it should be used judiciously.
These examples should provide you with a solid foundation to demonstrate your understanding of apply in NumPy and Pandas during a data science interview.