如何用Pandas从原Excel表格填充合并后DataFrame的NaN值?
当然可行!用Pandas的
fillna就能轻松解决这个问题,我来帮你一步步修正代码: 首先,先分析你遇到的问题:
- 你用
left merge以历史表为基准合并后,没有匹配到当前表的行(比如Photo ID=4)会出现NaN,但这些缺失值其实都能在你读取的historicalDataFrame里找到对应数据。 - 你之前的错误代码
photo_data.replace('NaN', "Historical Photos"["location"])有两个问题:一是"Historical Photos"是工作表名称字符串,不是你读取的DataFrame变量(你存在historical里);二是replace不适合填充缺失值,应该用专门的fillna方法。
修正后的完整代码:
import pandas as pd file_location = "H:\\Travel\\AC_Images.xlsx" test_xls = pd.ExcelFile(file_location) # 读取两个工作表(注意skiprows要确保表头正确读取) historical = test_xls.parse("Historical Photos", skiprows=1) current = test_xls.parse("Current Photos", skiprows=2) # 左合并:保留历史表的所有行,匹配当前表的数据 # 合并后重复列会自动加_x(历史表)和_y(当前表)后缀 photo_data = historical.merge(current, left_on="Photo ID", right_on="photonum", how="left") # 用历史表的数据填充当前表列的NaN值 # 比如:如果当前表的Type_y是空的,就用历史表的Type_x填充 photo_data['Type'] = photo_data['Type_y'].fillna(photo_data['Type_x']) # 日期列:用当前表的Taken填充,没有的话用历史表的Date photo_data['Date'] = photo_data['Taken'].fillna(photo_data['Date_x']) # 地点列:同理 photo_data['Location'] = photo_data['Location_y'].fillna(photo_data['Location_x']) # 保留你需要的最终列 photo_data = photo_data[['Photo ID', 'Type', 'Date', 'Location']] # 查看结果 print(photo_data)
关键说明:
- 合并后的列后缀:因为两个表有同名列(Type、Location),Pandas会自动给左表(历史表)的列加
_x,右表(当前表)的列加_y,这样你能明确区分来源。 fillna的用法:这个方法会自动识别列中的NaN值,并用你指定的数据源替换——这里我们直接用历史表的对应列(Type_x、Date_x)来填充当前表列(Type_y、Taken)的缺失值。- 如果想直接用整个历史表填充:如果合并后的DataFrame和
historical的行顺序完全一致(left merge默认会保留左表顺序),你也可以简化成:
这样所有NaN都会被历史表对应位置的值填充。photo_data = photo_data.fillna(historical)
你之前的错误原因:
- 你用字符串
"Historical Photos"去索引,这是工作表名称,不是存储数据的DataFrame变量(你存在historical里),所以会报string indices must be integers错误。 replace('NaN', ...)是替换字符串"NaN",而Pandas里的缺失值是pd.NA或np.nan,不是字符串,所以这个方法根本找不到要替换的内容。
这样处理后,你的合并结果里第4行的NaN就会被历史表的tiff、5/30/18、AUS正确填充啦!
内容的提问来源于stack exchange,提问作者Tiffany Morris
相关产品推荐
相关产品推荐

