python pandas合并Sheet,處理列亂序和出現(xiàn)Unnamed列的解決
使用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頁(yè)數(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ò)誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
Python循環(huán)語(yǔ)句之break與continue的用法
計(jì)算pytorch標(biāo)準(zhǔn)化(Normalize)所需要數(shù)據(jù)集的均值和方差實(shí)例
pyqt4教程之實(shí)現(xiàn)windows窗口小示例分享
Python+Selenium使用Page Object實(shí)現(xiàn)頁(yè)面自動(dòng)化測(cè)試
Python time庫(kù)的時(shí)間時(shí)鐘處理
python實(shí)現(xiàn)與arduino的串口通信的示例代碼

