是否可以在一个文件中读写多个DataFrame? [英] Is it possible to write and read multiple DataFrames to/from one single file?

查看:239
本文介绍了是否可以在一个文件中读写多个DataFrame?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在处理一组具有双Header的类似DataFrame. 它们具有以下结构:

I'm currently dealing with a set of similar DataFrames having a double Header. They have the following structure:

   age height weight shoe_size
   RHS height weight shoe_size
0  8.0    6.0    2.0       1.0
1  8.0    NaN    2.0       1.0
2  6.0    1.0    4.0       NaN
3  5.0    1.0    NaN       0.0
4  5.0    NaN    1.0       NaN
5  3.0    0.0    1.0       0.0

   height  weight shoe_size   age
      RHS  weight shoe_size   age
0     1.0    1.0        NaN   NaN
1     1.0    2.0        0.0   2.0
2     1.0    NaN        0.0   5.0
3     1.0    2.0        0.0   NaN
4     0.0    1.0        0.0   3.0

实际上,主要区别在于第一页标题行的排序(对于所有行都可以使其相同)以及RHS标头列在第二页标题行中的位置.我目前在想,是否有一种简单的方法可以将所有这些DataFrame保存到一个CSV文件中或从一个CSV文件中读取所有这些DataFrame,而不是为每个文件拥有一个不同的CSV文件.

Actually the main differences are the sorting of the first Header row, which could be made the same for all of them, and the position of the RHS header column in the second Header row. I'm currently wondering if there is an easy way of saving/reading all these DataFrames into/from a single CSV file instead of having a different CSV file for each of them.

推荐答案

不幸的是,没有任何合理的方法将多个数据帧存储在一个CSV中,这样检索每个数据帧不会太麻烦,但是您可以使用pd.ExcelWriter并保存到单个.xlsx文件中的单独图纸中:

Unfortunately, there isn't any reasonable way to store multiple dataframes in a single CSV such that retrieving each one would not be excessively cumbersome, but you can use pd.ExcelWriter and save to separate sheets in a single .xlsx file:

import pandas as pd

writer = pd.ExcelWriter('file.xlsx')
for i, df in enumerate(df_list):
    df.to_excel(writer,'sheet{}'.format(i))
writer.save() 

这篇关于是否可以在一个文件中读写多个DataFrame?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆