Spatial Digger
Spatial Digger

Reputation: 1993

looping through a dataframe to replace values

I'm trying to have terms in a dataframe, an old term (existing) and a new term that will replace it. This dataframe is then used in the replace() process. Runnig the following presents a keyerror error KeyError: "None of [Index([('HIS_COP_', ''), ('_Ply', ''), ('_Pt', '')], dtype='object')] are in the [columns]"

Manually this works:

    gdf['montype'].replace('HIS_COP_', '', regex=True, inplace=True)
    gdf['montype'].replace('_Ply', '', regex=True, inplace=True)
    gdf['montype'].replace('_Pt', '', regex=True, inplace=True)

code:

    montype = [['HIS_COP_', ''],
               ['_Ply', ''],
               ['_Pt','']]

    df = pd.DataFrame(montype, columns=['term_old', 'term_new'])

    for term in df:
        print(df)
        gdf[montype].replace(term['term_old'], term['term_new'], regex=True, inplace=True)

Upvotes: 1

Views: 35

Answers (1)

jezrael
jezrael

Reputation: 863611

Create dictionary from nested list and pass to replace:

gdf['montype' ] = gdf['montype' ].replace(dict(montype), regex=True)

I think inplace is not good practice, check this and this

Upvotes: 1

Related Questions