Python 依次将 2 个列表和 Pandas 个数据帧写入 csv/excel

Python write 2 lists and Pandas DataFrames to csv/excel sequentially

我有这些 Python 列表和 Pandas 数据框:

list_1 = ['Intro line here - record of method function:']
list_2 = ['Record of local minimum follows:']

print df_1
   Col_A    Col_B
  3.4443    1.443
 10.8876    11.99

print df2
Trial_1  Trial_2  Trial_3
    1.1     1.49    775.9
   11.5     9.57     87.3
 384.61   77.964     63.7
  12.49    0.156      1.9
 112.11   11.847    178.3

这是我想要的输出 csv 或 excel 文件 - csv 或 excel 都适合我:

Intro line here - record of method function:
   Col_A    Col_B
  3.4443    1.443
 10.8876    11.99
Record of local minimum follows:
Trial_1  Trial_2  Trial_3
    1.1     1.49    775.9
   11.5     9.57     87.3
 384.61   77.964     63.7
  12.49    0.156      1.9
 112.11   11.847    178.3

有没有办法把list,Pandas,list,Pandas按这个顺序写入csv或者excel文件?

csv module 提供您想要的功能:

import csv
with open('SO Example.csv', 'w') as f:
    writer = csv.writer(f, lineterminator='\n')
    writer.writerow(list_1)
    writer.writerow(df1.columns)
    writer.writerows(df1.values)
    writer.writerow(list_2)
    writer.writerow(df2.columns)
    writer.writerows(df2.values)

pd.to_csv() 接受文件句柄作为输入,而不仅仅是文件名。所以你可以打开一个文件句柄并将多个文件写入其中。这是一个例子:

from __future__ import print_function

with open('output.csv', 'w') as handle:
    for line in list_1:
        print(line, handle)
    df1.to_csv(handle, index=False)
    for line in list_2:
        print(line, handle)
    df2.to_csv(handle, index=False)