You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何优化Counter对象的双层for循环 实现DataFrame快速筛选

优化实现方案

原有代码运行极慢的核心原因是采用了三重嵌套循环、逐行删除数据、反复重置索引的操作,时间复杂度达到了O(M*N²)(M为DataFrame行数,N为counter_diff的键数量),完全没有利用pandas的向量化运算特性。使用如下方案可将运行时长压缩至秒级:

具体实现代码

import pandas as pd

# 1. 将counter_diff转为Series,用于快速映射查询频率
freq_s = pd.Series(counter_diff)

# 2. 给DataFrame两列的词映射对应的频率,缺失值默认填充为0(可根据需求调整)
df['freq_col0'] = df[0].map(freq_s).fillna(0)
df['freq_col1'] = df[1].map(freq_s).fillna(0)

# 3. 按照要求的过滤条件筛选行
filter_mask = ((df['freq_col0'] == 0) & (df['freq_col1'] > 0)) | ((df['freq_col0'] > 0) & (df['freq_col1'] == 0))
res_df = df[filter_mask].copy()

# 4. 清理临时列,重置索引
res_df = res_df.drop(columns=['freq_col0', 'freq_col1']).reset_index(drop=True)

额外说明

如果counter_diff不存在的词不需要默认补0,而是要直接排除,可以在映射后先删掉频率为空的行:

df = df.dropna(subset=['freq_col0', 'freq_col1'])

内容的提问来源于stack exchange,提问作者Radix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 01:45:01