Pandas DataFrame无法正确导出到CSV,缺少数据

在下面的代码中,我有一个进入函数的条目列表。

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')

When I print the DataFrame jam_df I get this,

             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零件?

评论
Clark
Clark

连接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')

see https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html?highlight=concat

点赞
评论
iut
iut

for循环中的内容运行了两次,一次用于“ APPL”,一次用于“ KO”。输出路径相同('jam_df.csv'),因此APPL的输出被覆盖。

点赞
评论