newbzzs
newbzzs

Reputation: 305

Updating index values column using dictionary

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

Upvotes: 1

Views: 370

Answers (1)

U13-Forward
U13-Forward

Reputation: 71560

You gave to convert it to a series:

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

Upvotes: 1

Related Questions