熊猫按分位数过滤导致空集

时间:2019-05-14 20:36:40

标签: python pandas filter

如何将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

3 个答案:

答案 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]