使用pandas df.query()在分类(区间)列上进行过滤

4

我想要使用对象(Object)区间(Interval) 类别(Category)列来筛选一个 dataframe。我想要根据多个条件进行筛选。如何在区间(Interval) 类别(Category) 数据下实现?

query函数返回多个区间。

>>> my_df
        vtype   velocity_bin
0         car  (-0.001, 5.0]
1         car    (5.0, 10.0]
2         car    (10.0, inf]
3  motorcycle  (-0.001, 5.0]
4  motorcycle    (5.0, 10.0]
>>> my_df.dtypes
vtype             object
velocity_bin    category
dtype: object
>>> my_df.query('vtype == "car" & velocity_bin == (5, 10)')
  vtype   velocity_bin
0   car  (-0.001, 5.0]
1   car    (5.0, 10.0]

我希望您能够输出以下内容:
  vtype   velocity_bin
1   car    (5.0, 10.0]
1个回答

4

你的"velocity_bin"列由区间对象组成。这会带来一定的挑战,因为query不容易支持它。

作为惯用解决方法,我建议使用:

df[(df['vtype'] == 'car') & (df['velocity_bin'] == pd.Interval(5, 10))]

然而,就像任何其他事物一样,您可以拼凑一个 查询 解决方案。使用 "python" 引擎,并将 "velocity_bin" 转换为字符串进行字符串比较,我们有:

df.query(
    'vtype="car" and velocity_bin.astype("str") == "(5.0, 10.0]"', engine='python')

不知道我们可以在 query() 中调用 astype(),这是一个很好的技巧 :) - anky

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