pandas dataframe with 2-rows header and export to csv

后端 未结 4 1188
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-11 03:29

I have a dataframe

df = pd.DataFrame(columns = [\"AA\", \"BB\", \"CC\"])
df.loc[0]= [\"a\", \"b\", \"c1\"]
df.loc[1]= [\"a\", \"b\", \"c2\"]
df.loc[2]= [\"a\         


        
4条回答
  •  温柔的废话
    2020-12-11 03:55

    Building on top of @DSM's solution:

    if you need (as I did) to apply the same hack to an export to excel, the main change needed (apart from expected differences with the to_excel method) is to actually remove the multiindex used for your column labels...

    That's because .to_excel doesn't support writing out a df having a multiindex for columns but no index (providing index=False to the .to_excel method) contrarily to .to_csv

    Anyway, here's what it would look like:

    >>> writer = pd.ExcelWriter("noblankrows.xlsx")
    >>> headers = pd.DataFrame(df.columns.tolist()).T
    >>> headers.to_excel(
            writer, header=False, index=False)
    >>> df.columns = pd.Index(range(len(df.columns)))  # that's what I was referring to...
    >>> df.to_excel(
            writer, header=False, index=False, startrow=len(headers))
    >>> writer.save()
    >>> pd.read_excel("noblankrows.xlsx").to_csv(sys.stdout, index=False)
    AA,BB,CC
    DD,EE,FF
    a,b,c1
    a,b,c2
    a,b,c3
    

提交回复
热议问题