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

yipeiwu_com6年前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中的文档测试模块

如果你经常阅读Python的官方文档,可以看到很多文档都有示例代码。比如re模块就带了很多示例代码: >>> import re >>> m =...

python 画3维轨迹图并进行比较的实例

python 画3维轨迹图并进行比较的实例

一. 数据的格式 首先我们需要x,y,z三个数据进行画图。从本实验用到的数据集KITTI 00.txt中举例: 1.000000e+00 9.043680e-12 2.326809e...

深入理解NumPy简明教程---数组2

NumPy数组(2、数组的操作) 基本运算 数组的算术运算是按元素逐个运算。数组运算后将创建包含运算结果的新数组。 >>> a= np.array([20,30...

python2和python3在处理字符串上的区别详解

python2和python3对于字符串的处理有很大的区别 熟悉了python2的写法用python3时真的会遇到很多问题啊…… 区别 python2中有一种类型叫做unicode型,例...

Window10+Python3.5安装opencv的教程推荐

Window10+Python3.5安装opencv的教程推荐

1.确定Python版本,电脑64位或者32位 打开cmd(window键+R,输入cmd就出现),在命令行输入:打开cmd(window键+R,输入cmd就出现),在命令行输入:pyt...