2

I want to add a new column to my dataframe and map it to a dictionary. Mapping should be on the index of my original dataframe and I don't know how to use .map() to get there.

d={'KO': 'Consumer, Non-cyclical', 'AAPL': 'Technology'}

df:

Date   2015-12-01   
KO    2144.499950  
AAPL  5162.959824  

I would like the result too look like this:

df:

Date   2015-12-01  industry 
KO    2144.499950  Consumer, Non-cyclical
AAPL  5162.959824  Technology

1 Answer 1

4

Construct the Series first:

df["industry"] = pd.Series(d)

Note: This assumes that the dict keys are in the DataFrame index:

In [11]: df
Out[11]:
       2015-12-01
KO    2144.499950
AAPL  5162.959824

In [12]: df["industry"] = pd.Series(d)

In [13]: df
Out[13]:
       2015-12-01                industry
KO    2144.499950  Consumer, Non-cyclical
AAPL  5162.959824              Technology
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Andy. This is good. I was about to reindex the df data frame and have it indexed with 0,1,2,3, ... . Then move KO, AAPL,.. to fist column and use map() afterwards.
A very basic question. What does the code In[11] and Out[11] mean?\
@Mugen it's ipython/jupyter syntax. highly recommended download. e.g. see ipython.readthedocs.io/en/stable/interactive/tutorial.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.