pandas dataframe with 2-rows header and export to csv

后端 未结 4 1191
爱一瞬间的悲伤
爱一瞬间的悲伤 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:40

    Use df.to_csv("test.csv", index = False, tupleize_cols=True) to get the resulting CSV to be:

    "('AA', 'DD')","('BB', 'EE')","('CC', 'FF')"
    a,b,c1
    a,b,c2
    a,b,c3
    

    To read it back:

    df2=pd.read_csv("test.csv", tupleize_cols=True)
    df2.columns=pd.MultiIndex.from_tuples(eval(','.join(df2.columns)))
    

    To get the exact output you wanted:

    with open('test.csv', 'a') as f:
        pd.DataFrame(np.asanyarray(df.columns.tolist())).T.to_csv(f, index = False, header=False)
        df.to_csv(f, index = False, header=False)
    

提交回复
热议问题