Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用yFinance向我的数据框添加列_Python_Pandas_Dataframe_Yfinance - Fatal编程技术网

Python 使用yFinance向我的数据框添加列

Python 使用yFinance向我的数据框添加列,python,pandas,dataframe,yfinance,Python,Pandas,Dataframe,Yfinance,初学者的问题来了,似乎无法连接点 我有一个名为my_pf的投资组合数据框架,其中包括我用来收集开盘价的股票。我通过接下来的两个步骤成功地收集了期初数据 #create a list from the column 'ticker' my_tickers = my_pf['ticker'].tolist() #collect the opening data per ticker for ticker in my_tickers: open_price = yf.Ticker(ticke

初学者的问题来了,似乎无法连接点

我有一个名为my_pf的投资组合数据框架,其中包括我用来收集开盘价的股票。我通过接下来的两个步骤成功地收集了期初数据

#create a list from the column 'ticker'
my_tickers = my_pf['ticker'].tolist()

#collect the opening data per ticker
for ticker in my_tickers:
    open_price = yf.Ticker(ticker).info.get('open')
    
    print(ticker, open_price)
下一步是将提取的数据添加到初始数据帧。但是我该怎么做呢


提前感谢您的帮助。

向列添加数据的方法有很多,例如df.append()和pd.concat(),但是我们使用df.append()创建了代码。我们从一个空数据框开始创建股票列和开盘价列。一旦我们有了开盘价,我们就将品牌名称和开盘价添加到我们刚刚创建的数据框中

import pandas as pd
import yfinance as yf

# my_tickers = my_pf['ticker'].tolist()
my_tickers = ['msft', 'aapl', 'goog']
tickers = yf.Tickers(my_tickers)

df = pd.DataFrame(index=[], columns=['ticker','Open'])
for ticker in my_tickers:
    open_price = yf.Ticker(ticker).info.get('open')
    df = df.append(pd.Series([ticker,open_price], index=df.columns), ignore_index=True)
    
print(df)

ticker  Open
0   msft    204.07
1   aapl    112.37
2   goog    1522.36

我很高兴我也能帮助你。请接受我的回答。