Improving readability of boolean indexing with the query method
Boolean indexing is not necessarily the most pleasant syntax to read or write, especially when using a single line to write a complex filter. Pandas has an alternative string-based syntax through the DataFrame query
method that can provide more clarity.
Note
The query
DataFrame method is experimental and not as capable as boolean indexing and should not be used for production code.
Getting ready
This recipe replicates the earlier recipe in this chapter, Translating SQL WHERE clauses, but instead takes advantage of the query
DataFrame method. The goal here is to filter the employee data for female employees from the police or fire departments that earn a salary between 80 and 120 thousand dollars.
How to do it...
- Read in the employee data, assign the chosen departments, and import columns to variables:
>>> employee = pd.read_csv('data/employee.csv') >>> depts = ['Houston Police Department-HPD', 'Houston...