大数量级下两个DataFrame高效匹配关联的方法咨询
高效提取DataFrame对应值的解决方案
原始数据结构
df1结构:
| Date | Name |
|---|---|
| 2022-01-01 | A |
| 2022-01-02 | A |
| 2022-01-03 | A |
| 2022-01-01 | B |
| 2022-01-02 | B |
| 2022-01-03 | B |
df2结构:
| Result | A | B | C |
|---|---|---|---|
| 2021-12-31 | False | True | True |
| 2022-01-01 | False | False | True |
| 2022-01-02 | False | True | False |
| 2022-01-03 | True | False | True |
需求说明
将df2中对应Date和Name的结果提取到df1中,生成新的Result列,预期结果如下:
| Date | Name | Result |
|---|---|---|
| 2022-01-01 | A | False |
| 2022-01-02 | A | False |
| 2022-01-03 | A | True |
| 2022-01-01 | B | False |
| 2022-01-02 | B | True |
| 2022-01-03 | B | False |
高效实现方法
放弃逐行循环,利用pandas的向量化操作和数据重塑完成,性能远优于循环方案:
步骤1:重塑df2为长格式
将df2的列名转为Name列,行索引转为Date列,让数据结构与df1匹配:
import pandas as pd # 重置df2的索引并转置,生成匹配df1的结构 df2_reshaped = df2.set_index('Result').stack().reset_index() df2_reshaped.columns = ['Date', 'Name', 'Result']
步骤2:合并两个DataFrame
用merge方法按Date和Name精准匹配,这是pandas内部优化的批量操作,大数据量下效率极高:
final_df = df1.merge(df2_reshaped, on=['Date', 'Name'], how='left')
简化版代码
若无需保留中间变量,可合并为一行:
final_df = df1.merge(df2.set_index('Result').stack().reset_index(name='Result'), on=['Date', 'Name'], how='left')
该方法完全依赖pandas的向量化运算,避免了Python层面的逐行遍历,在数据量庞大、频繁更新的场景下能显著缩短处理时间。
内容的提问来源于stack exchange,提问作者xyww
相关产品推荐
相关产品推荐

