Python按顺序将2个列表和Pandas DataFrames写入csv / excel

时间:2015-04-23 01:57:19

标签: python pandas export-to-excel export-to-csv

我有这些Python列表和Pandas Dataframes:

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

有没有办法按此顺序将列表,Pandas,list,Pandas写入csv或excel文件?

2 个答案:

答案 0 :(得分:2)

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)

答案 1 :(得分:2)

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)