Pandas 如果数据框中不存在替换中的术语,如何忽略它们?

Pandas 如果数据框中不存在替换中的术语,如何忽略它们?,pandas,replace,Pandas,Replace,我有以下代码用另一个术语替换一个术语,这仅在pandas数据帧中存在值时有效,我假设我需要在if语句中包装gdf[montype]=gdf[montype].replace(dict(montype),regex=True)?我该怎么做,还是有更好的方法 montype = [ ['HIS_COP_', ''], ['_Ply', ''], ['_Pt',''], ['BURIAL','burial'], [

我有以下代码用另一个术语替换一个术语,这仅在pandas数据帧中存在值时有效,我假设我需要在
if语句中包装
gdf[montype]=gdf[montype].replace(dict(montype),regex=True)
?我该怎么做,还是有更好的方法

    montype = [
        ['HIS_COP_', ''],
        ['_Ply', ''],
        ['_Pt',''],
        ['BURIAL','burial'],
        ['CUT', 'CUT'],
        ['MODERN', 'MODERN'],
        ['NATURAL', 'NATURAL'],
        ['STRUCTURE', 'STRUCTURE'],
        ['SURFACE', 'SURFACE'],
        ['TREETHROW', 'natural feature'],
        ['FURROW', 'FURROW'],
        ['FIELD_DRAIN', 'FIELD_DRAIN'],
        ['DEPOSIT_FILL', 'DEPOSIT_FILL'],
        ['POSTHOLE', ''],
        ['TIMBER', ''],
        ['', '']
    ]

    gdf[montype] = gdf[montype].replace(dict(montype), regex=True)
当该术语不存在时,我得到错误
raisekeyerror(f“没有[{key}]在[{axis\u name}]中”)

编辑:

您可以尝试以下方法:

# Convert you list to dict

Montype={'His_cop':'','Modern':'Modern', etc...} # dict(montype)

gdf[montype]=gdf[montype].map(Montype).fillna('whatever value you want')

将所有值转换为
nan
code编辑添加,并将Montype更改为mtypewith
.fillna()
添加后,nan将按预期更改,但它们仍作为上一条注释全部转换为nan。这意味着gdf['Montype']列不包含任何字典键。请发布您的数据帧示例
# Convert you list to dict

Montype={'His_cop':'','Modern':'Modern', etc...} # dict(montype)

gdf[montype]=gdf[montype].map(Montype).fillna('whatever value you want')