0

I have a dataframe which contains these columns - maxlevel, level1id, level2id, level3id.

I need to populate a new column - newcol_value based on the value from maxlevel column.

If maxlevel = 1, populate the newcol_value with level1id

If maxlevel = 2, populate the newcol_value with level2id

If maxlevel = 3, populate the newcol_value with level3id

I tried this.

id_dict = {1:'level1id', 2:'Level2ID', 3:'level3id', 4:'level4id', 5:'level5id'}
df['id'] = df[id_dict[df['maxlevel']]]

But as the df['maxlevel] is giving series, I'm getting the following error.

TypeError: 'Series' objects are mutable, thus they cannot be hashed

How can I fill the newcol_value values based on the value in maxlevel column?

Underoos
  • 4,708
  • 8
  • 42
  • 85
  • 2
    Possible duplicate of [Replace values in a pandas series via dictionary efficiently](https://stackoverflow.com/questions/49259580/replace-values-in-a-pandas-series-via-dictionary-efficiently) – Ben.T Aug 12 '19 at 18:11

1 Answers1

1

You should using lookup

d={'level1id':1, 'Level2ID':2, 'level3id':3, 'level4id':4, 'level5id':5}


df=df.rename(columns=d)
df['New']=df.lookup(df.index,df.maxlevel)
BENY
  • 317,841
  • 20
  • 164
  • 234