Get startedGet started for free

Looping using the .apply() function

1. Looping using the .apply() function

Great job on iterating through pandas DataFrames! We will now use the .apply() function to perform a specific task, while iterating through a pandas DataFrame.

2. The .apply() function

We'll keep using the poker dataset. The .apply() function does exactly what it says; it applies another function to the whole DataFrame. The syntax of the .apply() function is simple: we create a mapping, using a lambda function in this case, and then declare the function we want to apply to every cell. Here, we're applying the square root function to every cell of the DataFrame. In terms of speed, it matches the speed of just using the NumPy sqrt() function over the whole DataFrame.

3. The .apply() function for rows

But what happens when the function of interest is taking more than one cell as an input? For example, what if we want to calculate the sum of the rank of all the cards in each hand? In this case, we will use the .apply() function the same way as we did before, but we need to add 'axis=1' at the end of the line to specify we're applying the function to each row. The, we will use the .iterrows() function we saw on the previous lesson to do the same, and compare their efficiency. Using the .apply() function is significantly faster than the .iterrows() function, in a magnitude of around 400 percent, which is a massive improvement!

4. The .apply() function for columns

As we did with rows, we can do exactly the same thing for the columns; apply one function to each column. By replacing the axis=1 with axis=0, we can apply the sum function on every column. By comparing the .apply() function with the native pandas function for summing over rows, we can see that pandas' native .sum() functions performs the same operation faster. In conclusion, we observe that the .apply() function performs faster when we want to iterate through all the rows of a pandas DataFrame, but is slower when we perform the same operation through a column.

5. Let's do it!

Now that we saw the pros and cons of each application of the .apply() method, let's give it a try!

Create Your Free Account

or

By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.