在下面的代码中,我有一个进入函数的条目列表。
import yfinance as yf
import pandas as pd
import csv
jam_list = []
def price(ticker):
company = yf.Ticker(ticker)
price = company.history(period='max')
price_df = pd.DataFrame(price)
price_df.drop(price_df.columns[[0,1,2,4,5,6]], axis = 1, inplace = True)
price_df['tic'] = (ticker)
return price_df
l = ["AAPL", "KO"]
for ticker in l:
jam = price(ticker)
jam_list.append(jam)
jam_df = pd.DataFrame(jam)
print(jam_df)
jam_df.to_csv('jam_df.csv')
当我打印DataFrame jam_df
时,我得到了,
Close scoop
Date
1980-12-12 0.41 AAPL
1980-12-15 0.38 AAPL
... ... ...
2020-05-14 309.54 AAPL
2020-05-15 307.71 AAPL
[9940 rows x 2 columns]
Close scoop
Date
1962-01-02 0.00 KO
1962-01-03 0.00 KO
... ... ...
2020-05-14 43.70 KO
2020-05-15 43.26 KO
[14695 rows x 2 columns]
当我将其导出到csv文件时,我只会得到KO部分,即印刷版本的第二部分。如何使csv导出AAPL和KO?
答案 0 :(得分:2)
在连接df列表后,您需要在循环后导出
import yfinance as yf
import pandas as pd
import csv
jam_list = []
def price(ticker):
company = yf.Ticker(ticker)
price = company.history(period='max')
price_df = pd.DataFrame(price)
price_df.drop(price_df.columns[[0,1,2,4,5,6]], axis = 1, inplace = True)
price_df['tic'] = (ticker)
return price_df
l = ["AAPL", "KO"]
for ticker in l:
jam = price(ticker)
jam_list.append(jam)
jam_df = pd.DataFrame(jam)#useless
print(jam_df)
full_df = pd.concat(jam_list)
full_df.to_csv('jam_df.csv')
请参阅https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html?highlight=concat
答案 1 :(得分:0)
for循环中的内容运行了两次,一次用于“ APPL”,一次用于“ KO”。输出路径相同('jam_df.csv'),因此APPL的输出被覆盖。