在 IPython 中,我在常规数据帧上执行 groupby:
grouped
Out[356]: <pandas.core.groupby.DataFrameGroupBy object at 0x7f0e78578750>
但是 filter 似乎得到的是系列而不是数据帧:
...: def print_obj(x):
...: print type(x)
...: return True
...:
e=grouped.filter(print_obj)
<class 'pandas.core.series.Series'>
<class 'pandas.core.series.Series'>
<class 'pandas.core.series.Series'>
<class 'pandas.core.series.Series'>
<class 'pandas.core.series.Series'>
<class 'pandas.core.series.Series'>
<class 'pandas.core.series.Series'>
<class 'pandas.core.frame.DataFrame'>
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-349-a93d384d3560> in <module>()
----> 1 e=grouped.filter(print_obj)
/home/user/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()
但是,当我执行 apply 时,我只会获取数据帧:
grouped.apply(print_obj)
<class 'pandas.core.frame.DataFrame'>
...
filter 文档字符串说我应该获取数据帧。为什么?我该如何解决? (我只想从 grouped-by df 中删除一些组)。
附言 Pandas ==0.12.0
请您参考如下方法:
在内部,apply 和 filter 尝试不同的数据循环方式:肯定适用于任何函数的“慢速路径”和“快速路径” "仅适用于某些功能。这些路径可以对整个数据 block (作为 DataFrame)或一次一行(作为 Series)进行操作。
细节很微妙——如果你愿意,可以查看 pandas/core/groupby.py——但要点是 print_obj 揭示了其中的一些内部结构与您真正想做的事情无关。
您想删除哪些组,您尝试使用什么标准?
