为800万行Pandas DataFrame寻找向量化active列计算方案
向量化解决800万行DataFrame的活跃状态判断问题
核心思路
放弃逐行迭代的iterrows,改用向量化的合并与映射,利用Pandas底层的C优化逻辑批量处理数据,彻底解决性能瓶颈。
步骤1:整合月度活跃数据
先把分散的5个活跃表合并成带月份标识的统一表,方便后续批量关联:
import pandas as pd # 给每个活跃表添加对应的年月标识 active_12_2022['month'] = '2022-12' active_01_2023['month'] = '2023-01' active_02_2023['month'] = '2023-02' active_03_2023['month'] = '2023-03' active_04_2023['month'] = '2023-04' # 合并所有活跃表,去重确保每个客户-月份组合唯一 active_all = pd.concat( [active_12_2022, active_01_2023, active_02_2023, active_03_2023, active_04_2023], ignore_index=True ).drop_duplicates(subset=['Customer Number', 'month']) # 设置多级索引,加速后续关联查询 active_all = active_all.set_index(['Customer Number', 'month'])
步骤2:处理主表的日期字段
为每行数据生成需要检查的当前月份和上一个月份,同时处理早于2023年1月的特殊情况:
# 确保Date列是datetime类型(如果还不是的话) df['Date'] = pd.to_datetime(df['Date']) # 生成当前年月和上月年月(格式:YYYY-MM) df['current_month'] = df['Date'].dt.strftime('%Y-%m') df['prev_month'] = (df['Date'] - pd.DateOffset(months=1)).dt.strftime('%Y-%m') # 对早于2023年1月的行,强制使用最早的两个活跃表对应的月份 # 注:你原文提到的active_01_2022疑似笔误,这里用你提供的active_01_2023,若确实是2022年1月,替换为'2022-01'即可 mask_early = df['Date'] < '2023-01-01' df.loc[mask_early, ['current_month', 'prev_month']] = ['2022-12', '2023-01']
步骤3:批量关联并判断活跃状态
用两次merge批量关联当前月和上月的活跃状态,再通过布尔运算得到最终结果:
# 关联当前月的活跃状态,不存在的客户默认设为False df = df.merge( active_all['active'].rename('active_current'), left_on=['Customer Number', 'current_month'], right_index=True, how='left' ) df['active_current'] = df['active_current'].fillna(False) # 关联上月的活跃状态,不存在的客户默认设为False df = df.merge( active_all['active'].rename('active_prev'), left_on=['Customer Number', 'prev_month'], right_index=True, how='left' ) df['active_prev'] = df['active_prev'].fillna(False) # 只要两个月份任一活跃,就标记为True df['active'] = df['active_current'] | df['active_prev'] # 清理临时生成的辅助列 df.drop(['current_month', 'prev_month', 'active_current', 'active_prev'], axis=1, inplace=True)
性能说明
- 这种方式完全基于Pandas的向量化操作,底层由C实现,避免了
iterrows逐行处理的Python级循环开销,800万行数据的处理时间通常能压缩到几分钟内。 - 提前设置多级索引能大幅提升
merge的查询效率,避免全表扫描。
内容的提问来源于stack exchange,提问作者maiktheissen
相关产品推荐
相关产品推荐

