Filling a pandas column based on another column

偶尔善良 提交于 2019-12-24 01:56:12

问题


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.



来源:https://stackoverflow.com/questions/53859920/filling-a-pandas-column-based-on-another-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!