Pandas数据框中过滤“多个”组时速度慢?

1 投票
2 回答
2701 浏览
提问于 2025-04-18 17:05

我有一个大约有20万行的数据表,我想按照以下方式进行筛选:

>>> df.groupby(key).filter(lambda group: len(group) > 100)

这里的key是一些列的列表。当key指定的列把数据表分成大约800组时,这个操作大约需要3秒钟。但是,如果我再加一列到key中,把组的数量增加到大约2500组,执行这个操作就会占用我所有的内存,基本上会导致我的系统崩溃,除非我终止这个脚本。

我可以通过遍历这些组来做到这一点,但这样做比上面的一行代码要麻烦多了,这让我想知道为什么筛选函数会有这么大的限制。

有人能告诉我这是正常现象吗?如果是的话,为什么会这样呢?

谢谢!

2 个回答

1

我找到了解决办法。我的一个列里面有日期,我把这些日期表示成了时间戳对象。当我把这些时间戳对象转换成字符串时,分组就能快速顺利地进行!

1

这有点儿取决于你有多少组,但你遇到的情况可能还有其他原因。这种速度其实挺快的。

In [10]: N = 1000000

In [11]: ngroups = 1000

In [12]: df = DataFrame(dict(A = np.random.randint(0,ngroups,size=N),B=np.random.randn(N)))

In [13]: %timeit df.groupby('A').filter(lambda x: len(x) > 1000)
1 loops, best of 3: 431 ms per loop

In [14]: df.groupby('A').filter(lambda x: len(x) > 1000).info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 508918 entries, 0 to 999997
Data columns (total 2 columns):
A    508918 non-null int64
B    508918 non-null float64
dtypes: float64(1), int64(1)
In [15]: df = DataFrame(dict(A = np.random.randint(0,10,size=N),B=np.random.randn(N)))

In [16]: %timeit df.groupby('A').filter(lambda x: len(x) > 1000)
1 loops, best of 3: 182 ms per loop

In [17]: df.groupby('A').filter(lambda x: len(x) > 1000).info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1000000 entries, 0 to 999999
Data columns (total 2 columns):
A    1000000 non-null int64
B    1000000 non-null float64
dtypes: float64(1), int64(1)

撰写回答