Python Pandas - 将DataFrame独立地组合到Spreadsheets

时间:2018-03-22 19:52:54

标签: python pandas

我正在努力的问题是将数据框架相互结合,但保持它们彼此独立。例如:

df1 = data1.pivot_table(index=pd.to_datetime(data1['Date']), 
                              columns=['State','City'], values=metric) :
State       L.A.     L.A.   L.A.
City        Arcadia  Bell   Durate
2/22/2018   2.05     3.07   1.96
2/25/2018   4.82     2.56   3.14
3/2018      2.51     3.45   3.02

df2 = data2.pivot_table(index=pd.to_datetime(data2['Date']), 
                              columns=['State','City'], values=metric) :
State       G.A.     G.A.      G.A.
City        Athens   Atlanta   Macon
2/22/2018   1.56     3.25      1.97
2/25/2018   3.92     3.66      1.28
3/2018      3.61     1.25      3.42

当我连接它们时,数据就像这样并排配对:

State       L.A.     L.A.   L.A.     G.A.     G.A.      G.A.
City        Arcadia  Bell   Durate   Athens   Atlanta   Macon
2/22/2018   2.05     3.07   1.96
2/25/2018   4.82     2.56   3.14
3/2018      2.51     3.45   3.02

2/22/2018                            1.56     3.25      1.97
2/25/2018                            3.92     3.66      1.28
3/2018                               3.61     1.25      3.42

我的问题是,是否有办法格式化数据,使其最终看起来像这样

State       L.A.     L.A.   L.A.
City        Arcadia  Bell   Durate
2/22/2018   2.05     3.07   1.96
2/25/2018   4.82     2.56   3.14
3/2018      2.51     3.45   3.02
State       G.A.     G.A.      G.A.
City        Athens   Atlanta   Macon
2/22/2018   1.56     3.25      1.97
2/25/2018   3.92     3.66      1.28
3/2018      3.61     1.25      3.42

谢谢!

1 个答案:

答案 0 :(得分:0)

您会考虑将每个数据框保存到单个.xlsx文件中,只需将每个框架放在前一个框架下面吗?

import pandas as pd

save_path = "path\\to\\the\\excel_file.xlsx"
writer = pd.ExcelWriter(save_path)
all_frames = [df1, df2, dfn]  # all of your dataframes

counter = 0
for df in all_frames:
    df.to_excel(writer, startrow=counter, index=True)
    counter += df.shape[0]

这应该会产生一个包含所需输出的.xlsx文件,如上所示:

State       L.A.     L.A.   L.A.
City        Arcadia  Bell   Durate
2/22/2018   2.05     3.07   1.96
2/25/2018   4.82     2.56   3.14
3/2018      2.51     3.45   3.02
State       G.A.     G.A.      G.A.
City        Athens   Atlanta   Macon
2/22/2018   1.56     3.25      1.97
2/25/2018   3.92     3.66      1.28
3/2018      3.61     1.25      3.42