Home > Blockchain >  Need to change all values in a pandas column but getting key error
Need to change all values in a pandas column but getting key error

Time:06-11

Update: Looks like I'm getting the KeyError because I did df.rename(columns={'doc_id' : 'UniqueId'}) but this only created an alias name. I need to match the schema of another table for an append operation downstream. Both answers worked if I used 'doc_id'. I suppose I should repost for how to permanently change column names in the dataframe.

I thought this would be straight forward but I'm getting hung up. I have a bunch of unique IDs in brackests and I need to join the data frame with another table using the same IDs that have no brackets; hence I would like to remove the brackets from the target dataframe. The field, or series if you will, is called 'UniqueId'. I have verified this several times.

Initially I tried this:

df['UniqueId'].replace(df['UniqueId'], df['UniqueId'][1:-1])

Then this:

df['UniqueId'].replace('{',)

which would have been followed by:

df['UniqueId'].replace('}',)

either way I get a key error.

Here is the latest one:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
In  [49]:
Line 1:     df['UniqueId'].replace('{',)

File C:\Program Files\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\Lib\site-packages\pandas\core\frame.py, in __getitem__:
Line 3024:  indexer = self.columns.get_loc(key)

File C:\Program Files\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\Lib\site-packages\pandas\core\indexes\base.py, in get_loc:
Line 3082:  raise KeyError(key) from err

KeyError: 'UniqueId'

What must I do?

CodePudding user response:

Try this using regex to search for opening or closing parenthesis, and replacing with null.

df['UniqueId'] = df['UniqueId'].replace(r'\{|\}','', regex=True)

CodePudding user response:

Just use .str.strip

df['UniqueId'] = df['UniqueId'].str.strip('{}')
  • Related