如何基于另一DataFrame的索引与列名实现更高效的映射函数?
问题描述
我有一个包含Subtype和Building Condition列的DataFrame(Dataframe 1):
| Subtype | Building Condition |
|---|---|
| A | Good |
| B | Bad |
| C | Bad |
希望基于这两列的值,通过另一个DataFrame(Dataframe 2)完成映射:
| Good | Bad | |
|---|---|---|
| A | Repair | Retrofit |
| B | Retrofit | Reconstruct |
| C | Reconstruct | Reconstruct |
当前我通过遍历Dataframe 1,使用pd.DataFrame.at函数逐行获取映射值并添加到列表,最终生成新列Intervention,代码如下:
# assignment of intervention based on subtype and building condition intervention_list = [] for index, row in bldg_df.iterrows(): # print(bldg_df.at[index, 'Subtype']) intervention = matrix_df.at[bldg_df['Subtype'][index], bldg_df['Building Condition'][index]] intervention_list.append(intervention) bldg_df['Intervention'] = intervention_list
最终得到的结果DataFrame:
| Subtype | Building Condition | Intervention |
|---|---|---|
| A | Good | Repair |
| B | Bad | Reconstruct |
| C | Bad | Reconstruct |
这个方法可行,但想寻求更高效的实现方式,比如使用map或merge_asof函数?
高效实现方案
方法1:映射表转嵌套字典后用apply匹配
先把Dataframe 2转换为嵌套字典,再通过行数据直接匹配取值:
# 将matrix_df转为嵌套字典:{Subtype: {Condition: Intervention}} map_dict = matrix_df.to_dict('index') # 对bldg_df每行应用匹配逻辑 bldg_df['Intervention'] = bldg_df.apply(lambda x: map_dict[x['Subtype']][x['Building Condition']], axis=1)
该方式利用Pandas向量化操作替代逐行遍历,数据量越大,效率提升越明显。
方法2:重塑映射表后用merge关联
将宽格式的Dataframe 2转为长格式,再通过merge完成关联匹配:
# 把matrix_df从宽表转为长表 matrix_long = matrix_df.stack().reset_index() matrix_long.columns = ['Subtype', 'Building Condition', 'Intervention'] # 合并两个DataFrame,匹配对应干预措施 bldg_df = bldg_df.merge(matrix_long, on=['Subtype', 'Building Condition'], how='left')
merge是Pandas原生高效关联操作,适合需要保留更多关联信息的场景。
方法3:向量化索引取值(性能最优)
利用索引位置匹配,结合Numpy向量化操作直接取值,是性能最高的方案:
import numpy as np # 获取Subtype和Building Condition在映射表中的索引位置 row_idx = matrix_df.index.get_indexer(bldg_df['Subtype']) col_idx = matrix_df.columns.get_indexer(bldg_df['Building Condition']) # 通过Numpy向量化操作提取对应值 bldg_df['Intervention'] = np.take_along_axis(matrix_df.values, col_idx[:, None], axis=1).flatten()
该方案完全规避循环,依赖底层向量化运算,处理大规模数据时优势显著。
内容的提问来源于stack exchange,提问作者John Lawrence Abarquez
相关产品推荐
相关产品推荐

