Boolean selection

Items in a Series can be selected, based on the value instead of index labels, via the utilization of a Boolean selection. A Boolean selection applies a logical expression to the values of the Series and returns a new Series of Boolean values representing the result for each value. The following code demonstrates identifying items in a Series where the values are greater than 5:

In [58]:
   # which rows have values that are > 5?
   s = pd.Series(np.arange(0, 10))
   s > 5

Out[58]:
   0    False
   1    False
   2    False
   3    False
   4    False
   5    False
   6     True
   7     True
   8     True
   9     True
   dtype: bool

To obtain the rows in the Series where the logical expression is True, simply pass the result of the Boolean expression to the [] operator of the Series. The ...

Get Learning pandas now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.