How to create a new column in pandas based on a conditional that references a dictionary

David Eccles :

I have stock data that I am trying to normalize but I am having an issue with creating a new column. I need to be able to add a value to the new column called Yahoo Ticker by referencing what is in the Ticker column and getting the corresponding value from the dictionary, using the Ticker value as the key. Here is a sample of the dictionary I am using:

dict = {'AAB': 'AAB.TO',
        'ABX': 'ABX.TO',
        'XDU': 'XDU-U.TO' }

I want to add a column to my dataframe with the value based off the dictionary key so for example I want to turn this dataframe:

df = pd.DataFrame({'Ticker':['AAB','ABX','XDU'] })

into a dataframe like this:

newdf = pd.DataFrame({'Ticker':['AAB','ABX','AAV'],
                      'Yahoo Ticker':['AAB.TO','ABX.TO','XDU-U.TO']})

Previously I tried this but it didn't work

for index, value in df.iterrows():
    df.loc[df['Ticker'][index] in ticker_dictionary, 'Yahoo Tickers'] = ticker_dictionary[value]
Dani Mesejo :

You could use map:

import pandas as pd

df = pd.DataFrame({'Ticker': ['AAB', 'ABX', 'XDU']})

d = {'AAB': 'AAB.TO',
     'ABX': 'ABX.TO',
     'XDU': 'XDU-U.TO'}

df['Yahoo Ticker'] = df['Ticker'].map(d)
print(df)

Output

  Ticker Yahoo Ticker
0    AAB       AAB.TO
1    ABX       ABX.TO
2    XDU     XDU-U.TO

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=394891&siteId=1
Recommended