使用python中的pandas,xlrd,openpyxl庫(kù)完成合并excel中指定sheet的操作
# -*- coding: UTF-8 -*-
import xlrd
import pandas as pd
from pandas import DataFrame
from openpyxl import load_workbook
#表格位置
excel_name = '1.xlsx'
# 獲取workbook中所有的表格
wb = xlrd.open_workbook(excel_name)
#獲取sheets
sheets = wb.sheet_names()
# 循環(huán)所需sheet
newdata = DataFrame()
#in后()里填寫需要合并的sheet頁數(shù)
for i in (3,4,5):
df = pd.read_excel(excel_name, sheet_name=(i-1), header = None,index_col=0,encoding='utf-8')
newdata = newdata.append(df,ignore_index = False)
#保存為新的sheet,首先新建sheet,合并后的數(shù)據(jù)保存到新sheet中
writer = pd.ExcelWriter('1.xlsx',engin='openpyxl')
book = load_workbook(writer.path)
writer.book = book
#利用dataframe.to_excel保存合并后的數(shù)據(jù)到新的sheet,生成新的sheet命名為newdata
newdata.to_excel(excel_writer=writer,sheet_name="newdata")
writer.save()
writer.close()
print('處理完成!')
其中
df = pd.read_excel(excel_name, sheet_name=(i-1), header = None,index_col=0,encoding='utf-8')
需要指定 header = None,否則會(huì)出現(xiàn)如下warning:
FutureWarning: Sorting because non-concatenation axis is not aligned. A future version
of pandas will change to not sort by default.
并且生成的新sheet中的列會(huì)出現(xiàn)亂序以及Unnamed列。
補(bǔ)充:pandas 中讀取和寫入csv文件時(shí)候出現(xiàn)Unnamed:0的解決方案
在讀取csv文件的時(shí)候,默認(rèn)會(huì)自動(dòng)添加新的一列,Unnamed:0
解決方案:
read_csv()時(shí)候,設(shè)置index_col=0即可。
在寫入csv文件的時(shí)候,默認(rèn)會(huì)自動(dòng)加入新的一列,Unnamed:0
解決方案:
to_csv()時(shí)候,設(shè)置index=False。或者加上index=True, index_label="id"
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
您可能感興趣的文章:- 利用python Pandas實(shí)現(xiàn)批量拆分Excel與合并Excel
- 解決python3安裝pandas出錯(cuò)的問題
- Python機(jī)器學(xué)習(xí)三大件之二pandas
- Python Pandas知識(shí)點(diǎn)之缺失值處理詳解
- Python基礎(chǔ)之pandas數(shù)據(jù)合并
- python基于Pandas讀寫MySQL數(shù)據(jù)庫(kù)
- python 使用pandas同時(shí)對(duì)多列進(jìn)行賦值
- Python3 pandas.concat的用法說明
- python pandas模糊匹配 讀取Excel后 獲取指定指標(biāo)的操作
- Python數(shù)據(jù)分析之pandas讀取數(shù)據(jù)