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