1

I want to create a new column on a pandas dataframe using values on the index and a dictionary that translates these values into something more meaningful. My initial idea was to use map. I arrived to a solution but it is very convoluted and there must be a more elegant way to do it. Suggestions?

#dataframe and dict definition
df=pd.DataFrame({'foo':[1,2,3],'boo':[3,4,5]},index=['a','b','c'])
d={'a':'aa','b':'bb','c':'cc'}

df['new column']=df.reset_index().set_index('index',drop=False)['index'].map(d)
2
  • Can you give some more information on your desired output? Commented Mar 1, 2018 at 19:25
  • Umm... df['new column'] = df.index.to_series().map(d) is one way... Commented Mar 1, 2018 at 19:30

2 Answers 2

1

Creating a new series explicitly is a bit shorter:

df['new column'] = pd.Series(df.index, index=df.index).map(d)
Sign up to request clarification or add additional context in comments.

Comments

0

After to_series, you can using map or replace

df.index=df.index.to_series().map(d)
df
Out[806]: 
    boo  foo
aa    3    1
bb    4    2
cc    5    3

Or we think about another way

df['New']=pd.Series(d).get(df.index)
df
Out[818]: 
   boo  foo New
a    3    1  aa
b    4    2  bb
c    5    3  cc

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.