w3resource

Pandas Series: searchsorted() function

Find indices where elements should be inserted to maintain order

The searchsorted() function is used to find indices where elements should be inserted to maintain order.

Find the indices into a sorted Series self such that, if the corresponding elements in value were inserted before the indices, the order of self would be preserved.

Syntax:

Series.searchsorted(self, value, side='left', sorter=None)
Pandas Series searchsorted image
Name Description Type/Default Value Required / Optional
value Values to insert into self. array_like Required
side If ‘left’, the index of the first suitable location found is given. If ‘right’, return the last such index. If there is no suitable index, return either 0 or N (where N is the length of self).

{‘left’, ‘right’} Optional
sorter Optional array of integer indices that sort self into ascending order. They are typically the result of np.argsort. 1-D array_like Optional

Returns: int or array of int- A scalar or array of insertion points with the same shape as value. Changed in version 0.24.0: If value is a scalar, an int is now always returned. Previously, scalar inputs returned an 1-item array for Series and Categorical.

Notes:

Binary search is used to find the required insertion points.

Example:

Python-Pandas Code:

import numpy as np
import pandas as pd
x = pd.Series([2, 3, 4])
x

Output:

0    2
1    3
2    4
dtype: int64
Pandas Series searchsorted image

Python-Pandas Code:

import numpy as np
import pandas as pd
x = pd.Series([2, 3, 4])
x.searchsorted(3)

Output:

1

Python-Pandas Code:

import numpy as np
import pandas as pd
x = pd.Series([2, 3, 4])
x.searchsorted([2, 4])

Output:

array([0, 2], dtype=int64)

Python-Pandas Code:

import numpy as np
import pandas as pd
x = pd.Series([2, 3, 4])
x.searchsorted([2, 3], side='left')

Output:

array([0, 1], dtype=int64)

Python-Pandas Code:

import numpy as np
import pandas as pd
x = pd.Series([2, 3, 4])
x.searchsorted([2, 3], side='right')

Output:

array([1, 2], dtype=int64)

Python-Pandas Code:

import numpy as np
import pandas as pd
x = pd.Categorical(['tea', 'bread', 'butter', 'milk'], ordered=True)
x.searchsorted('butter')

Output:

2

Python-Pandas Code:

import numpy as np
import pandas as pd
x = pd.Categorical(['tea', 'bread', 'butter', 'milk'], ordered=True)
x.searchsorted(['bread'], side='right')

Output:

array([2], dtype=int64)

Previous: Explode list-likes including lists, tuples, Series, and np.ndarray
Next: Repeat elements of a Pandas series



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/pandas/series/series-searchsorted.php