python - 使用 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
.
有没有办法可以并行化这个过程或更有效地把它分解成碎片?
解决方案
实际答案取决于您想对 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
推荐阅读
- node.js - 如何使用 React ckfinder Node.js 上传图像
- android - 使用Android Navigation Component,如何使actionBar透明并在单个Fragment中使布局全屏?
- python - PyPDF4 - 导出的 PDF 文件太大
- ios - 无法在测试框架中使用 XCTUnwrap
- android - 我们如何在android中的两个活动之间传递扩展类的对象?
- pyspark - 在python中以编程方式提交pyspark作业而不使用提交pyspark
- laravel - 具有多个连接的数据库查询的雄辩查询
- python - python中的初学者错误,如何修复这种“lat”类型
不能转换为浮动 - python - 如果变音符号位于行尾,如何在变音符号后添加空格
- html - 如何修复 CSS 网格区域以在 IE11 中工作?