Pandas数据帧与multindex卓越

时间:2017-04-10 21:46:15

标签: python excel python-2.7 pandas export-to-excel

我试图搞定这个

enter image description here

但我得到了这个:

enter image description here

即使没有内容,我也会获得垂直多索引。这是我正在做的事情的MWE

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

1 个答案:

答案 0 :(得分:0)

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

取自我的编辑