首页 > 解决方案 > 使用 Pandas 通过唯一索引过滤大型数据帧

问题描述

我有一个 3000 万行 x 30 列的数据框,我想使用唯一索引列表进行过滤。

基本上输入是:

df = pd.DataFrame({'column':[0,1,2,3,4,5,6,7,8,9,10]})
indices = [1, 7, 10]

df_filtered = df[df.index.isin(indices)]

输出为:

df_filtered

column
1
7
10

这适用于“可管理”数据框,但是当尝试将 (30,000,000, 30) 数据框与约 33,000 个唯一索引列表匹配时,这会让我进入本地MemoryError.

有没有办法可以并行化这个过程或更有效地把它分解成碎片?

标签: pythonpython-3.xpandasdataframeout-of-memory

解决方案


实际答案取决于您想对 DataFrame 做什么,但遇到内存错误时的一般想法是分块执行操作。

在您的情况下,大小为 N 的块是列表中的 N 个顺序元素indices

df = pd.DataFrame()  # placeholder for your huge dataframe
indices = []  # placeholder for your long list of indices

chunksize = 50  # size of each chunk (50 rows)

for chunk in range(0, len(indices), chunksize):
    current_indices = indices[chunk:chunk+chunksize]
    df_filtered = df[df.index.isin(current_indices)]
    # do what you want with df_filtered here

推荐阅读