如何将pandas.Series
切为分位数,并通过分位数仓进行过滤?我在这里使用的三种不同方法要么全部失败,要么导致空集。
所需的解决方案将使用df.query()
df = pd.DataFrame({'my_series':[1,2,3,4,5,6,7]})
df['quantile'] = pd.qcut(df.my_series, [0,0.5,0.6,1])
print(df)
#df[df.quantile == '(4.6, 7.0]'] # fails with key error :false
df['string_quantiles'] = df['quantile'].astype(object)
print(df)
display(df[df['string_quantiles'] == '(4.6, 7.0]']) # no failure, but empty set
df.query("my_series == '(0.999, 4.0]'") # empty set
答案 0 :(得分:5)
添加astype
进行转换
yourdf=df[df['string_quantiles'].astype(str)=='(4.6, 7.0]'].copy()
Out[60]:
my_series quantile string_quantiles
4 5 (4.6, 7.0] (4.6, 7.0]
5 6 (4.6, 7.0] (4.6, 7.0]
6 7 (4.6, 7.0] (4.6, 7.0]
或
df[df['quantile'].map(lambda x : x.left)==4.6].copy()
答案 1 :(得分:4)
pd.cut
返回Interval
个对象。因此,只需创建一个并进行比较:
df[df['quantile'] == pd.Interval(4.6, 7)]
my_series quantile
4 5 (4.6, 7.0]
5 6 (4.6, 7.0]
6 7 (4.6, 7.0]
答案 2 :(得分:4)
您可以使用codes
的{{1}}属性
Categorical
知道了
df[df['quantile'].cat.codes == 2]
my_series quantile
4 5 (4.6, 7.0]
5 6 (4.6, 7.0]
6 7 (4.6, 7.0]