如何基于Pandas DataFrame DF1修改DF2的值并设置Class列
解决方案
步骤1:构建Code与hasCode?的映射字典
先把DF1转换成键为Code(与DF2列名匹配)、值为hasCode?的字典,方便后续快速替换:
import pandas as pd import numpy as np # 统一Code类型:DF1的Code如果是数值型,转成字符串匹配DF2的列名 code_map = df1.set_index(df1['Code'].astype(str))['hasCode?'].to_dict()
步骤2:替换DF2中的"x"为对应hasCode?值
复制DF2作为DF3的基础,批量替换所有Code列中的"x":
df3 = df2.copy() # 筛选出所有Code列(排除Class列) code_cols = [col for col in df3.columns if col != 'Class'] # 高效批量替换:先把"x"替换为列名,再通过映射字典转成hasCode?值 df3[code_cols] = df3[code_cols].replace('x', df3[code_cols].columns) df3[code_cols] = df3[code_cols].apply(lambda col: col.map(code_map))
如果数据量较小,也可以用循环逐个列替换,逻辑更直观:
for col in code_cols: df3[col] = df3[col].apply(lambda val: code_map[col] if val == 'x' else val)
步骤3:设置Class列的值
根据每行替换后的结果,按规则判断Class列取值:
# 标记每行是否存在"yes"或"no" has_yes = df3[code_cols].eq('yes').any(axis=1) has_no = df3[code_cols].eq('no').any(axis=1) # 按优先级赋值:有yes则为Yes,否则有no则为no,无有效值则为empty df3['Class'] = np.where(has_yes, 'Yes', np.where(has_no, 'no', 'empty'))
完整示例验证
假设你的初始数据如下:
df1 = pd.DataFrame({ 'hasCode?': ['yes', 'no', 'no', 'no', 'yes'], 'Code': [2051, 2052, 2053, 2086, 2418] }) df2 = pd.DataFrame({ 'Class': ['', '', '', ''], '2051': ['x', '', '', 'x'], '2052': ['', '', 'x', 'x'], '2053': ['', '', 'x', ''], '2086': ['', '', '', ''], '2418': ['x', '', '', 'x'] })
运行代码后得到的DF3结果:
| Class | 2051 | 2052 | 2053 | 2086 | 2418 | |
|---|---|---|---|---|---|---|
| 0 | Yes | yes | yes | |||
| 1 | empty | |||||
| 2 | no | no | no | |||
| 3 | Yes | yes | no | yes |
内容的提问来源于stack exchange,提问作者TheMcFloyd
相关产品推荐
相关产品推荐

