我通过串联3个4列数据帧创建了一个多索引数据帧:
df = pd.concat([df_RCB, df_SECB, df_UBP], axis=1, sort=True)
headers = (['RCB']*4) + (['SECB']*4) + (['UBP']*4)
sub-headers = df.columns.tolist()
data = np.array(df)
data = pd.DataFrame(data=data, columns=pd.MultiIndex.from_tuples(list(zip(headers, sub-headers))), index=df.index)
data.head()
输出:
RCB SECB UBP
open high low close open high low close open high low close
1999-02-04 25.0 25.0 25.0 25.0 14.25 14.50 13.75 13.75 15.5 15.5 15.25 15.5
1999-02-05 25.0 25.0 25.0 25.0 13.75 13.75 13.75 13.75 15.5 15.5 15.50 15.5
1999-02-08 25.0 25.0 25.0 25.0 13.75 13.75 13.75 13.75 15.5 15.5 15.50 15.5
1999-02-09 25.0 25.0 25.0 25.0 13.75 13.75 13.75 13.75 15.5 15.5 15.50 15.5
1999-02-10 25.0 25.0 25.0 25.0 13.75 13.75 13.75 13.75 15.5 15.5 15.50 15.5
我将其写入csv文件,然后读取,但格式已更改:
data.to_csv('fin.csv', index_label=False)
fin = pd.read_csv('fin.csv')
fin.head()
输出:
Unnamed: 0 RCB RCB.1 RCB.2 RCB.3 SECB SECB.1 SECB.2 SECB.3 UBP UBP.1 UBP.2 UBP.3
0 NaN open high low close open high low close open high low close
1 1999-02-04 25.0 25.0 25.0 25.0 14.25 14.5 13.75 13.75 15.5 15.5 15.25 15.5
2 1999-02-05 25.0 25.0 25.0 25.0 13.75 13.75 13.75 13.75 15.5 15.5 15.5 15.5
3 1999-02-08 25.0 25.0 25.0 25.0 13.75 13.75 13.75 13.75 15.5 15.5 15.5 15.5
4 1999-02-09 25.0 25.0 25.0 25.0 13.75 13.75 13.75 13.75 15.5 15.5 15.5 15.5
在写入csv之前,如何保留数据帧的格式?
答案 0 :(得分:0)
如果要保留多重索引,应该写excel而不是csv
data.to_excel('fin.xlsx')
您还可以通过
创建数据df = pd.concat([df_RCB, df_SECB, df_UBP],keys=['RCB','SECB','UBP'] axis=1, sort=True)