如何用Python对比更新两个Excel指定列?及NaN异常排查
需求与异常问题
需求说明
我有两个结构一致的Excel文件,均包含col1至col9列,数据示例如下:
file1
| col1 | col2 | col3 | col4 | col5 | col6 | col7 | col8 | col9 |
|---|---|---|---|---|---|---|---|---|
| server1 | java_yes | .... | .... | .... | .... | .... | .... | .... |
| server2 | java_no | .... | .... | .... | .... | .... | .... | .... |
| server4 | java_no | .... | .... | .... | .... | .... | .... | .... |
| server8 | java_no | .... | .... | .... | .... | .... | .... | .... |
file2
| col1 | col2 | col3 | col4 | col5 | col6 | col7 | col8 | col9 |
|---|---|---|---|---|---|---|---|---|
| server1 | java_yes | .... | .... | .... | .... | .... | .... | .... |
| server3 | java_no | .... | .... | .... | .... | .... | .... | .... |
| server4 | java_yes | .... | .... | .... | .... | .... | .... | .... |
| server8 | java_no | .... | .... | .... | .... | .... | .... | .... |
需要完成以下操作:
- 遍历file1
- 将file1中col1的每个条目与file2的col1进行匹配
- 若匹配成功,检查两者的col2值是否一致
- 若col2值不一致,将file1的col2值更新为file2的col2值
异常问题
运行代码时出现异常:多数条目处理正常,但部分条目明明在DataFrame的col2列中值为java_yes,最终却显示为NaN。为排查问题,我在df1、df2及合并等多个阶段添加过滤器打印结果,各阶段均显示正常的Yes,但最后打印df1时,部分条目显示NaN。
使用的过滤代码如下:
my_filter = ( df1['col1'] == 'server1' ) print(df1.loc[my_filter, 'col2'])
内容的提问来源于stack exchange,提问作者user1074593
相关产品推荐
相关产品推荐

