Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/26.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 将具有多索引的数据框转换为excel_Python_Excel_Python 2.7_Pandas_Export To Excel - Fatal编程技术网

Python 将具有多索引的数据框转换为excel

Python 将具有多索引的数据框转换为excel,python,excel,python-2.7,pandas,export-to-excel,Python,Excel,Python 2.7,Pandas,Export To Excel,我正试着弄到这个 但我明白了: 即使没有内容,我也会得到一个垂直多重索引。这是我正在做的一件事 from pandas import DataFrame, MultiIndex, ExcelWriter, Series import numpy.random as rd FILENAME = 'SampleFile.xlsx' writer = ExcelWriter(FILENAME, engine='xlsxwriter') multindex_headers = [['A', 'B'

我正试着弄到这个

但我明白了:

即使没有内容,我也会得到一个垂直多重索引。这是我正在做的一件事

from pandas import DataFrame, MultiIndex, ExcelWriter, Series
import numpy.random as rd

FILENAME = 'SampleFile.xlsx'
writer = ExcelWriter(FILENAME, engine='xlsxwriter')
multindex_headers = [['A', 'B', 'C', 'D'],
                     ['A1', 'B2','C3', 'D4']]

index = MultiIndex.from_tuples( list(zip(*multindex_headers)),  names=['l1','l2'])
sampleDF = DataFrame(index=index)
sample_info = [rd.randn(4).tolist()]*5

for sample_data in sample_info:
    sampleDF = sampleDF.append(DataFrame(sample_data, index=index))

sampleDF.to_excel(writer, sheet_name='case')
writer.save()
编辑:

我已经用transpose()实现了一个变通方法,但我想知道是否有正式的方法来解决这个问题:

from pandas import DataFrame, MultiIndex, ExcelWriter, Series
import numpy.random as rd

FILENAME = 'SampleFile.xlsx'
writer = ExcelWriter(FILENAME, engine='xlsxwriter')
multindex_headers = [['A', 'B', 'C', 'D'],
                     ['A1', 'B2','C3', 'D4']]

index = MultiIndex.from_tuples( list(zip(*multindex_headers)))
sampleDF = DataFrame(index=index)
sampleDF = sampleDF.transpose()
sample_info = [rd.randn(4).tolist()]*5

for sample_data in sample_info:
     sampleDF = sampleDF.append(DataFrame(sample_data, index=index).transpose())

#sampleDF.to_csv('samplecsv.csv')
sampleDF.to_excel(writer, sheet_name='case')
writer.save()
摘自我的编辑


摘自我的编辑

请再次查看数据框。这就是我所看到的。请再次查看数据帧。这就是我所看到的。
 from pandas import DataFrame, MultiIndex, ExcelWriter, Series
import numpy.random as rd

FILENAME = 'SampleFile.xlsx'
writer = ExcelWriter(FILENAME, engine='xlsxwriter')
multindex_headers = [['A', 'B', 'C', 'D'],
                     ['A1', 'B2','C3', 'D4']]

index = MultiIndex.from_tuples( list(zip(*multindex_headers)))
sampleDF = DataFrame(index=index)
sampleDF = sampleDF.transpose()
sample_info = [rd.randn(4).tolist()]*5

for sample_data in sample_info:
     sampleDF = sampleDF.append(DataFrame(sample_data, index=index).transpose())

#sampleDF.to_csv('samplecsv.csv')
sampleDF.to_excel(writer, sheet_name='case')
writer.save()