Search⌘ K

Filtering with Function and .loc

Explore how to filter pandas DataFrames by passing functions into the .loc accessor. Understand the advantages of using .loc for selecting rows and columns, especially in chaining operations. Compare the differences between .loc and query methods to choose the best approach for your data filtering needs.

We'll cover the following...

Please be aware that we can pass in a boolean array and a function into loc. Here, we select rows with Average_rank less than ten and the first three columns:

Python 3.8
print(pres
.loc[pres.Average_rank < 10, lambda df_: df_.columns[:3]]
)

An advantage of passing a function into loc is that the function will receive the ...