Pandas Series: between() function
Boolean Series in Pandas
The between() function is used to get boolean Series equivalent to left <= series <= right.
This function returns a boolean vector containing True wherever the corresponding Series element is between the boundary values left and right. NA values are treated as False.
Syntax:
Series.between(self, left, right, inclusive=True)
Parameters:
Name | Description | Type/Default Value | Required / Optional |
---|---|---|---|
left | Left boundary. | scalar | Required |
right | Right boundary. | scalar | Required |
inclusive | Include boundaries. | bool Default Value: True |
Required |
Returns: Series
Series representing whether each element is between left and right (inclusive).
Notes: This function is equivalent to (left <= ser) & (ser <= right)
Example - Boundary values are included by default:
Python-Pandas Code:
import numpy as np
import pandas as pd
s = pd.Series([2, 0, 5, 9, np.nan])
s.between(1, 4)
Output:
0 True 1 False 2 False 3 False 4 False dtype: bool
Example - With inclusive set to False boundary values are excluded:
Python-Pandas Code:
import numpy as np
import pandas as pd
s = pd.Series([2, 0, 5, 9, np.nan])
s.between(1, 4, inclusive=False)
Output:
0 True 1 False 2 False 3 False 4 False dtype: bool
Example - left and right can be any scalar value:
Python-Pandas Code:
import numpy as np
import pandas as pd
s = pd.Series(['Abhi', 'Boby', 'Jhonny', 'Rio'])
s.between('Anny', 'Danis')
Output:
0 False 1 True 2 False 3 False dtype: bool
Previous: Compute the lag-N autocorrelation in Pandas
Next: Trim values at input in Pandas
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics