Home > database >  Updating index values column using dictionary
Updating index values column using dictionary

Time:10-14

So I've read a few helpful posts on this, but I still can't figure out what I'm doing wrong. I have a dictionary and I would like to use it to update the index of a dataframe which is made up of a bunch of different names.

If a name is present in a index of the dataframe and in the dictionary then I replace it with the new name. If its not present, then instead of replacing with nan, I keep the current name.

This is what I've tried so far:

First attempt:

df.index = df.index.map(dictt).fillna(df.index)

Error:

'value' must be scalar, passed: Index

Second attempt

df.index = df.index.replace(dictt)

Error:

'Index object has no attribute 'replace'

Third attempt

x = dictt.keys()
for name in df.index:
    if name in x:
    df.index[name].map(dictt)

Error:

only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

CodePudding user response:

You gave to convert it to a series:

df.index = df.index.map(dictt).to_series(index=df.index).fillna(df.index.to_series())
  • Related