问题描述
我想根据另一列中的条目填充数据框列的每一行,特别是我想用该股票的相应股票代码的相应名称填充每一行,就像这样
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:
所以我可以为 MSFT 取名:
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]}]
我正在努力寻找一种使用 for 循环或应用自动执行此操作的方法.任何人都可以建议一种方法吗?
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
推荐答案
可以先创建一个系列映射:
You can first create a series mapping:
ticker_name_map = get_nasdaq_symbols()['Security Name'].str[:-15]
然后使用pd.Series.地图
:
df1['Name'] = df1['ticker'].map(ticker_name_map)
如果您希望未映射的值保持不变,请使用后续的fillna
:
If you wish unmapped values to remain unchanged, then use a subsequent fillna
:
df1['Name'] = df1['ticker'].map(ticker_name_map).fillna(df1['Name'])
pd.Series.replace
也是可能的,但是 低效.
这篇关于根据另一列填充 pandas 列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!