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

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

我有这些 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

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

最佳答案

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)

关于Python 按顺序将 2 个列表和 Pandas DataFrame 写入 csv/excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29812246/

相关文章:

php - 将 html(填充 mysql)表导出到 excel 文件

python - Selenium:删除 cookie 时出现问题

python - EGL 驱动程序消息(错误)eglQueryDeviceAttribEXT : Bad attribute

python - 将外部源的数据同步到 django 项目中使用的数据库?

Python,将多行连接成一行

javascript - 如何将数据表导出到在 IE 中也适用的 Excel

python - 如何在 Windows XP 上使用 pip 安装 selenium 包?

python - 我如何量化 Pandas 中的数据?

python - 将系列与 DataFrame 相乘,其中 series.index == dataframe.columns

javascript - 我正在使用 calrketm/TableExport ,为什么 xlsx 按钮没有显示?