我通过连接 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 之前数据帧的格式?
最佳答案
如果你想保留多重索引,你应该写入 Excel 而不是 csv
data.to_excel('fin.xlsx')
<小时/>
您还可以通过以下方式创建数据
df = pd.concat([df_RCB, df_SECB, df_UBP],keys=['RCB','SECB','UBP'] axis=1, sort=True)
关于python - 将多索引数据帧写入 csv 而不更改其格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55997689/