保存结果到已存在的excel文件中

保存结果到已存在的excel文件中

网易云课堂该课程链接地址

https://study.163.com/course/courseMain.htm?share=2&shareId=400000000398149&courseId=1006383008&_trace_c_p_k2_=cd6d8636673a4b03b5f77ca55979c1a7

仅存单个excel表格就用df.to_excel更简单

pd.ExcelWriter保存结果到已存在的excel文件中,并支持多个sheet表格写入excel。

Python对excel更多功能编程需要安装openpyxl第三方包

Python代码如下

# -*- coding: utf-8 -*-
"""
Created on Sat Nov 30 13:24:28 2019

@author: [email protected]
"""
import numpy as np
import pandas as pd

df1 = pd.DataFrame({"name": ['Alfred', 'Batman', 'Catwoman'],
                   "toy": [np.nan, 'Batmobile', 'Bullwhip'],
                 "born": [pd.NaT, pd.Timestamp("1940-04-25"),
                           pd.NaT]})

df2 = pd.DataFrame({"name": ['Alfred', 'Jim', 'Catwoman'],
                   "toy": [np.nan, 'Batmobile', 'Bullwhip'],
                 "born": ['Greens',pd.Timestamp("1940-04-25"),
                           pd.NaT]})

with pd.ExcelWriter('result.xls') as writer:
    df1.to_excel(writer, sheet_name='sheet1')
    df2.to_excel(writer, sheet_name='sheet2')


#仅存单个excel表格就用to_excel更简单
df1.to_excel("result.xlsx")

  

微信扫二维码,免费学习更多python资源

12-25 09:53