A boolean series is a pandas Series of True and False values, usually produced by applying a comparison or test to every element of another Series. Think of it as a row-by-row checklist: True marks values that meet a condition, and False marks values to leave out. Because the result keeps the original index, it can be used directly to select matching values. section 1.13 section 9.0
The usual pattern is to build a condition and pass it to loc. First evaluate the expression inside the brackets: s < 30 produces a boolean series. Then loc uses that series as a mask index, returning only positions marked True. A mask selects data; it does not transform the selected values. section 1.13
A mask acts like a sieve: each boolean aligns with one Series value, and only True positions pass through. section 1.13
Select values at or below the mean
For s = Series([10, 20, 30, 40, 50]), use s.loc[s <= s.mean()]. The mean is computed as a scalar, the comparison is broadcast across s to create booleans, and loc returns the matching values. The same mask can appear on the left side of an assignment to update all selected positions at once. section 1.13 section 1.7
With a DataFrame, a boolean series commonly chooses rows. Put the row condition before the comma in loc, then name the columns to keep after it. For example, df.loc[df['sales'] > df['sales'].mean(), ['product_id', 'name']] finds above-average products while returning only the requested fields. section 2.14 section 2.8
Build more useful masks by combining elementwise tests:
- Use & when both conditions must be True, such as payment type 2 and total amount above 1000; wrap each comparison in parentheses. section 3.2
- Use | when either condition can match, such as either of two negative-value columns. section 13.3
- Use ~ to reverse a boolean series, such as keeping undergraduate institutions that are not also graduate institutions. section 13.3
- Use isin to test membership in a set of values, and str.isdigit or str.contains to create masks from textual content. section 2.22 section 9.0
Masks also support focused analysis. Filter taxi rides by an outlier condition and then inspect passenger_count only for those rows; filter a large imported DataFrame and count the matching passenger records; or identify dirty strings that can safely be converted to integers. The useful habit is to separate the question that creates the boolean series from the selection or calculation that consumes it. section 2.18 section 3.2 section 5.5
Find distinct schools without graduate programs
Create undergraduate and graduate school-name Series, test membership with ug_schools.isin(grad_schools), negate it with ~, and apply the result back to ug_schools. Calling drop_duplicates afterward turns matching program rows into a list of distinct institutions. section 13.3
