问题
I have these Python lists and 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
Here is what I want in the output csv or excel file - either csv or excel would work for me:
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
Is there a way to write the list, Pandas, list, Pandas in this order to the csv or excel file?
回答1:
pd.to_csv()
accepts a file handle as input, not just a file name. So you can open a file handle and write multiple files into it. Here's an example:
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)
回答2:
The csv module provides your desired functionality:
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)
来源:https://stackoverflow.com/questions/29812246/python-write-2-lists-and-pandas-dataframes-to-csv-excel-sequentially