Filling a pandas column based on another column

2019-07-09 02:26发布

问题:

I would like to fill each row of a column of my dataframe based on the entries in another column, in particular I want to fill each row with the corresponding name of the corresponding ticker for that stock, like so

dict1 = [{'ticker': 'AAPL','Name': 'Apple Inc.'},
 {'ticker': 'MSFT','Name': 'Microsoft Corporation'}]

df1 = pd.DataFrame(dict1)

This function provides the name for a given ticker:

So I can pull the name for for say MSFT:

dict1 = [{'ticker': 'AAPL','Name': 'Apple Inc.'},
 {'ticker': 'MSFT','Name': get_nasdaq_symbols().loc['MSFT'].loc['Security Name'][:-15]}]

I am struggling to find a way to automate this with a for loop or apply. Can anyone suggest an approach?

Note, the function used to pull the name comes from here:

 from pandas_datareader.nasdaq_trader import get_nasdaq_symbols

回答1:

You can first create a series mapping:

ticker_name_map = get_nasdaq_symbols()['Security Name'].str[:-15]

Then use pd.Series.map1:

df1['Name'] = df1['ticker'].map(ticker_name_map)

If you wish unmapped values to remain unchanged, then use a subsequent fillna:

df1['Name'] = df1['ticker'].map(ticker_name_map).fillna(df1['Name'])

1 pd.Series.replace is also possible, but inefficient.