Pandas如何检查Series值是否在区间内?

5

有没有更好的方法来检查pandas Series值是否在pandas区间内:

import pandas as pd, numpy as np
x = pd.Series(np.linspace(4.0,7.8,num=20))
i = pd.Interval(5.0, 6.0, closed='left')

result = (i.left<=x) & (x<i.right)

有没有可能不显式访问 i.lefti.righti.closed 来计算结果呢? 比如 x.isin(i)x in i

感谢您的帮助!


2
你写的代码是最快的解决方案,因为它使用了向量化的代码。你可以使用 x.map(i.__contains__),但在大型序列上速度会慢大约300倍。 - Code Different
1个回答

1
你可以使用 pandas.cut() 来实现这个功能:
bins=[5.0,6.0]
pd.cut(x,bins,right=False).dropna()
5    [5.0, 6.0)
6    [5.0, 6.0)
7    [5.0, 6.0)
8    [5.0, 6.0)
9    [5.0, 6.0)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接