首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用熊猫更改excel工作表的名称

用熊猫更改excel工作表的名称
EN

Stack Overflow用户
提问于 2018-04-25 11:04:30
回答 1查看 12.3K关注 0票数 3
代码语言:javascript
复制
import pandas as pd
import numpy as np
df = pd.read_excel(r"C:\Users\venkagop\Subbu\promo validation testing\P 02. Promotions-UK C1.xls")
df = df[['Promotions', 'Promotions: AE', 'Promotions: Anaplan ID', 'Promotions: Is Optima Scenario?', 'Promotions: SIDs', 'Set Inactive?', 'Start Date', 'End Date', 'Promo Period', 'Promo Optima Status', 'Change Promo Status']]
df = df[(df['Promo Period'] == 'FY1819')]
df = df[(df['Set Inactive?'] == 0 ) & (df['Promotions: Is Optima Scenario?'] == 1)]
df.dropna(subset=['Promotions: SIDs'], inplace=True)
df['Optima vs Anaplan Promo Status Validation'] = ""
df['Optima vs Anaplan Promo Status Validation'] = np.where(df['Promo Optima Status'] == df['Change Promo Status'], 'True', 'False')
df.to_excel(r"C:\Users\venkagop\Subbu\mytest.xls", index = False)
#after this i want to change sheeet1 name to some other name#
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-04-25 11:19:39

有两种方法可以解决这个问题。

方法1

使用sheet_name参数从一开始就将excel文件保存到正确的工作表名称。

代码语言:javascript
复制
import pandas as pd

writer = pd.ExcelWriter(r'C:\Users\venkagop\Subbu\mytest.xls')
df.to_excel(writer, sheet_name='MySheetName', index=False)
writer.save()

方法2

如果无法实现方法1,则在稍后阶段使用openpyxl更改工作表名称。此方法的优点是可以再次将pandas数据转换为Excel格式的成本。

代码语言:javascript
复制
import openpyxl

file_loc = r'C:\Users\venkagop\Subbu\mytest.xls'

ss = openpyxl.load_workbook(file_loc)
ss_sheet = ss.get_sheet_by_name('Sheet1')
ss_sheet.title = 'MySheetName'
ss.save(file_loc)
票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50020659

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档