我正在尝试使用提供的示例在熊猫中过滤groupby结果:
http://pandas.pydata.org/pandas-docs/dev/groupby.html#渗滤
但收到以下错误(熊猫0.12):
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-12-d0014484ff78> in <module>()
1 grouped = my_df.groupby('userID')
----> 2 grouped.filter(lambda x: len(x) >= 5)
/Users/zz/anaconda/lib/python2.7/site-packages/pandas/core/groupby.pyc in filter(self, func, dropna, *args, **kwargs)
2092 res = path(group)
2093
-> 2094 if res:
2095 indexers.append(self.obj.index.get_indexer(group.index))
2096
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
这是什么意思,如何解决?
编辑:代码来复制熊猫0.12稳定中的问题
dff = pd.DataFrame({'A': list('222'), 'B': list('123'), 'C': list('123') })
dff.groupby('A').filter(lambda x: len(x) > 2)
这是0.12中的一个准错误,并将在0.13中修复,现在res受类型检查保护:
if isinstance(res,(bool,np.bool_)):
if res:
add_indices()
我不太确定您是怎么得到这个错误的,但是,文档实际上是通过实际的熊猫编译并运行的。您应该确保您正在阅读正确版本的文档(在这种情况下,您链接的是开发者而不是稳定者-尽管API基本上没有变化)。
该标准的解决办法是使用这个做的改造,在这种情况下会是这样的:
In [11]: dff[g.B.transform(lambda x: len(x) > 2)]
Out[11]:
A B C
0 2 1 1
1 2 2 2
2 2 3 3
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句