0

I have a Python pandas dataframe that looks like this:

      year_2000  year_1999  year_1998  year_1997  year_1996  year_1995 (MANH, stock name)
MANH 454.47     -71.90     nan        nan        nan        nan         TEST             
LH   385.52     180.95     -24.14     -41.67     -68.92     -26.47      TEST             
DGX  373.33     68.04      4.01       nan        nan        nan         TEST             
SKX  306.56     nan        nan        nan        nan        nan         TEST 

where the stock tickers are the index. I want to add the name of each stock as a new column

I tried adding the stock name column via yearly_best['MANH','stock name']='TEST' but it adds the same name in all rows.

I have a dictionary called ticker_name which contains the tickers and the names

Out[65]: 
{'TWOU': '2U',
 'MMM': '3M',
 'ABT': 'Abbott Laboratories',
 'ABBV': 'AbbVie Inc.',
 'ABMD': 'Abiomed',
 'ACHC': 'Acadia Healthcare',
 'ACN': 'Accenture',
 'ATVI': 'Activision Blizzard',
 'AYI': 'Acuity Brands',
 'ADNT': 'Adient',

thus I would like to get the names from the dict and put then in a column in the dataframe. How can I do that?

2 Answers 2

2

As the key of your dictionnary are index of your dataFrame you can try:

d = {'TWOU': '2U',
'MMM': '3M',
'ABT': 'Abbott Laboratories',
'ABBV': 'AbbVie Inc.',
'ABMD': 'Abiomed',
'ACHC': 'Acadia Healthcare',
'ACN': 'Accenture',
'ATVI': 'Activision Blizzard',
'AYI': 'Acuity Brands',
'ADNT': 'Adient',}

df['stock name'] = pd.Series(d)
Sign up to request clarification or add additional context in comments.

Comments

1

You can try:

# Create a new column "stock_name" with the index values
yearly_best['stock_name'] = yearly_best.index
# Replace the "stock_name" values based on the dictionary
yearly_best['stock_name'].map(ticker_name, inplace=True)

Note that in this case, the dataframe's indices will remain as they were (stock tickers). If you would like to replace the indices with row numbers, consider using reset_index

Comments

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.