鍍金池/ 問答/人工智能  數(shù)據(jù)分析&挖掘  Python  Office/ pandas如何在已有excel的sheet里完全覆蓋地寫入數(shù)據(jù)?pandas如

pandas如何在已有excel的sheet里完全覆蓋地寫入數(shù)據(jù)?pandas如何刪除excel里的一行數(shù)據(jù)?

在使用pandas進(jìn)行文件寫入時(shí),如果原來sheet已有數(shù)據(jù),則新寫入數(shù)據(jù)在原來數(shù)據(jù)上進(jìn)行不刪除地復(fù)寫。比如說原來有4行數(shù)據(jù),我想刪掉一行,read為dataframe后drop掉一行,得到3行新的數(shù)據(jù),再次to_excel后只覆蓋了前3行,表格中的第4行還在。
怎樣才能夠真正地刪除掉excel中的一行使得行數(shù)-1?
我刪掉0行后寫入第123行,原來第3行還在。
clipboard.png

以下是我的代碼(參照了stackoverflow上“對(duì)一個(gè)sheet寫入而不影響其他sheeets的方法”).

# 讀取后drop
data = pd.read_excel("data.xlsx", sheetname=sheet_name)
mydata = data.drop([0], axis=0)
# 保存新的數(shù)據(jù)
book = load_workbook('data.xlsx')
writer = pd.ExcelWriter('data.xlsx',engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
mydata.to_excel(writer, "mysheet")
writer.save()
回答
編輯回答
維他命

如果要全部覆蓋的話, 可以把原來的數(shù)據(jù)全部清除, 然后把新數(shù)據(jù)寫入.
具體代碼:

# 讀取后drop
data = pd.read_excel("data.xlsx", sheet_name=sheet_name)
mydata = data.drop([0], axis=0)
# 保存新的數(shù)據(jù)
book = load_workbook('data.xlsx')
writer = pd.ExcelWriter('data.xlsx',engine='openpyxl')
writer.book = book
# 清除原來的數(shù)據(jù)
idx = book.sheetnames.index('mysheet')
book.remove(book.worksheets[idx])
book.create_sheet('mysheet', idx)

writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
mydata.to_excel(writer, “mysheet”)
writer.save()

參考:How to clear a range of values in an Excel workbook using OpenPyXl
注意, 這樣會(huì)把原來mysheet的所有其它數(shù)據(jù)清除!

2017年5月14日 20:03