gpt4 book ai didi

python - groupby.filter 适用于系列而不是数据帧? ( Pandas )

转载 作者:太空宇宙 更新时间:2023-11-04 03:51:57 24 4
gpt4 key购买 nike

在 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

最佳答案

在内部,applyfilter 尝试不同的数据循环方式:肯定适用于任何函数的“慢速路径”和“快速路径” "仅适用于某些功能。这些路径可以对整个数据 block (作为 DataFrame)或一次一行(作为 Series)进行操作。

细节很微妙——如果你愿意,可以查看 pandas/core/groupby.py——但要点是 print_obj 揭示了其中的一些内部结构与您真正想做的事情无关。

您想删除哪些组,您尝试使用什么标准?

关于python - groupby.filter 适用于系列而不是数据帧? ( Pandas ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20888921/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com