如何导入具有多级列索引的 csv

How to import csv with multi level column index

当我在 yahoo finance 中导入不止一只股票时,我得到了一个 multindex。我正在尝试导出为 csv 文件,它们导入具有相同索引的相同数据集。我尝试在 .to_csv 方法中使用 index = False,但它删除了行索引,这是我不想要的。

基本上我找不到让 stocks_sample_csvstocks_sample 具有相同索引的方法。

import pandas as pd
from datetime import date
import yfinance as yf

list_symbols = ["CERS", "CERU", "CETV", "CEVA", "CFA", "CFBK",
                "CFFI", "CFFN", "CFGE", "CFNB", "CFNL", "CFO",
                "CFRX", "CFRXW", "CFRXZ", "CG", "CGEN", "CGIX",
                "CGNX", "CGO", "CHCI", "CHCO", "CHDN", "CHEF",
                "CHEV", "CHFC", "CHFN", "CHI", "CHKE", "CHKP", 
                "CHLN", "CHMG", "CHNR", "CHOP", "CHRS", "CHRW",
                "CHSCM", "CHSCN", "CHSCO", "CHSCP"]
start = date(2017, 10, 1)
end = date(2020, 6, 25)

stocks_sample = yf.download(list_symbols, start, end, group_by='ticker')

#for checking 
print(stocks_sample)
stocks_sample.columns.levels[0]
stocks_sample.columns.levels[1]

stocks_sample.to_csv('stocks_sample.csv')
stocks_sample_csv = pd.read_csv('stocks_sample.csv')

#now check the imported .csv file
print(stocks_sample_csv)
stocks_sample_csv.columns.levels[0]
stocks_sample_csv.columns.levels[1]

顺便说一下,我这样做是为了不需要每次打开 python 控制台时都下载。

如有任何帮助,我们将不胜感激。

尝试以下更改-

stocks_sample = stocks_sample.reset_index() #will create the multi index as separate columns
stocks_sample.to_csv('stocks_sample.csv')

#while importing 
stocks_sample_csv = pd.read_csv('stocks_sample.csv')
stocks_sample_csv.set_index(['index0', 'index1']) #change the list to the list of columns which contain the previous indexes.