pandas分别写入excel的不同sheet方法

yipeiwu_com5年前Python基础

pandas可以非常方便的写数据到excel,那么如何写多个dataframe到不同的sheet呢?

使用pandas.ExcelWriter

import pandas as pd
 
writer = pd.ExcelFile('your_path.xlsx')
 
df1 = pd.DataFrame()
df2 = pd.DataFrame()
 
df1.to_excel(writer, sheet_name='df_1')
df2.to_excel(writer, sheet_name='df_2')
 
writer.save()

网上的大部分答案基本上都是这些内容,但是这里有个大坑,你会发现找不到想要的xlsx文件。

那么问题出在哪?

我们看看ExcelWriter源码就知道了

class ExcelFile(object):
  """
  Class for parsing tabular excel sheets into DataFrame objects.
  Uses xlrd. See read_excel for more documentation
  Parameters
  ----------
  io : string, path object (pathlib.Path or py._path.local.LocalPath),
    file-like object or xlrd workbook
    If a string or path object, expected to be a path to xls or xlsx file
  engine: string, default None
    If io is not a buffer or path, this must be set to identify io.
    Acceptable values are None or xlrd
  """

这里已经说的很清楚了,希望传入的是excel的路径,你只传了个文件名,当然找不到了。

而且从这里我们可以看到,pandas.ExcelWriter实质上是用xlrd来解析excel的。这个wrapper提供了更简单的接口。

以上这篇pandas分别写入excel的不同sheet方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python中zip()方法应用实例分析

本文实例分析了python中zip()方法的应用。分享给大家供大家参考,具体如下: 假设有一个集合set, 需要对set中的每个元素指定一个唯一的id,从而组建成一个dict结构。 这个...

python操作excel的方法

摘要: Openpyxl是一个常用的python库,用于对Excel的常用格式及其模板进行数据读写等操作。 简介与安装openpyxl库 Openpyxl is a Python lib...

解决python nohup linux 后台运行输出的问题

遇到问题 nohup python flush.py & 这样运行,生成了nohup.out文件,但是内容始终是空的,试了半天也不行。浪费了不少时间。 原因 python的输出又缓...

Python延时操作实现方法示例

本文实例讲述了Python延时操作实现方法。分享给大家供大家参考,具体如下: 在日常的开发中,往往会遇到这样的需求,需要某一个函数在一段时间之后才执行以达到某种特定的效果。此时,我们就需...

python3安装crypto出错及解决方法

首先我用的python3.5的版本 问题的由来,我想通过python去实现RSA加密算法时,破解某网站的js加密认证,网上说需要安装pycrypto,我就去进行pip安装了 pip...