python - How to create a new column in pandas based on a conditional that references a dictionary
问题描述
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]
解决方案
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
推荐阅读
- python - ucrtbase.DLL 因异常代码崩溃:40000015
- php - 检查密码是否包含使用 php 的简单序列
- javascript - 如何使用 `html()` 将文本插入元素?
- angular - 如何从预建主题中获取按钮颜色?
- sas - SAS 在日志中打印一个值
- python - 使用元组作为缓存键的 Python 函数中的手动记忆
- optaplanner - Optaplanner:根据 PlanningSolution 属性动态定义约束
- assembly - 理解从简单的 Rust 结构生成的程序集
- python - 属性错误:无法获取属性“BrainSet”
在朱庇特 - git - 一个实例中的 IntelliJ Git 结帐损坏了另一个实例中打开的项目