如何用Pandas链式语句实现外连接并自定义来源标识
用Pandas链式语句实现外连接并自定义来源标签
直接用链式调用就能一步完成外连接、标签映射和默认列删除的操作,完整代码如下:
import pandas as pd # 链式操作实现需求 result = (pd.merge(oran, other, on='Name', how='outer', indicator=True) .assign( Source=lambda df: df['_merge'].map({ 'left_only': 'oran only', 'right_only': 'other only', 'both': 'Both' }) ) .drop(columns='_merge'))
代码说明:
- 外连接并生成来源标记:
pd.merge的indicator=True参数会自动生成_merge列,标记每条数据是来自左表(left_only)、右表(right_only)还是两表共有(both) - 自定义来源标签:用
.assign新增Source列,通过map方法将默认标签映射为你需要的可读性名称 - 删除默认标记列:最后用
.drop移除不需要的_merge列
整个流程通过链式调用串联,无需分步创建临时变量,代码更简洁易读。
内容的提问来源于stack exchange,提问作者veg2020
相关产品推荐
相关产品推荐

