如何使用整数列表元素查询 python3 数据框

How to query python3 dataframe with integer list elements

这几天一直被一个问题卡住了,如果有人能帮忙,我将不胜感激。

我有一个数据框,其中有一列填充了整数列表项。

例如单列dataframe:

>>> df=pd.DataFrame({'a':[[1, 2, 3], [2, 4, 5], [1, 7, 8]]})

>>> df
           a
0  [1, 2, 3]
1  [2, 4, 5]
2  [1, 7, 8]

我想 运行 对数据框的查询 select 其元素包含特定值的行。 "in" 运算符不适用于此操作。 我定义了一个函数 func,我在查询

中调用它
>>> def func(l, v):
...     return l.apply(lambda val: v in val)

然后当我调用查询时,它在 python 3.6.3 上按预期工作(xubuntu 默认安装,通过 pip3 进行一些更新)。它 returns 唯一包含值 7 的行,例如

>>> df.query('@func(a, 7)')
           a
2  [1, 7, 8]

然而,当我在 python 3.6.4 上 运行 时,包含在最后一个 anaconda 版本中,它失败并显示以下消息:'Series' objects是可变的,因此它们不能被散列

>>> df.query('@func(a, 7)') Traceback (most recent call last):   File "<stdin>", line 1, in <module>   File
"/home/cedric/.local/lib/python3.6/site-packages/pandas/core/frame.py",
line 2297, in query
    res = self.eval(expr, **kwargs)   File "/home/cedric/.local/lib/python3.6/site-packages/pandas/core/frame.py",
line 2366, in eval
    return _eval(expr, inplace=inplace, **kwargs)   File "/home/cedric/.local/lib/python3.6/site-packages/pandas/core/computation/eval.py",
line 295, in eval
    ret = eng_inst.evaluate()   File "/home/cedric/.local/lib/python3.6/site-packages/pandas/core/computation/engines.py",
line 76, in evaluate
    res = self._evaluate()   File "/home/cedric/.local/lib/python3.6/site-packages/pandas/core/computation/engines.py",
line 122, in _evaluate
    _check_ne_builtin_clash(self.expr)   File "/home/cedric/.local/lib/python3.6/site-packages/pandas/core/computation/engines.py",
line 31, in _check_ne_builtin_clash
    names = expr.names   File "/home/cedric/.local/lib/python3.6/site-packages/pandas/core/computation/expr.py",
line 755, in names
    return frozenset([self.terms.name])   File "/home/cedric/.local/lib/python3.6/site-packages/pandas/core/generic.py",
line 1045, in __hash__
    ' hashed'.format(self.__class__.__name__)) TypeError: 'Series' objects are mutable, thus they cannot be hashed

我希望我的函数能够在我使用的任何 python3 (>= 3.6) 上运行。也许我做错了。任何帮助将不胜感激。

编辑 1: 我在这两种情况下都使用 pandas 0.22.0。

解决方案: 我找到了解决办法。出现这个问题是因为anaconda的query函数默认engine='numexpr'。当设置engine='python'时,它又起作用了。

看来问题是因为anaconda默认的查询函数engine='numexpr'。当设置engine='python'时,它又起作用了。

我仍然不明白为什么它不适用于 numexpr 引擎,但我可以接受。