如何使用Python Pandas(Dataframes)从多个Excel文件中删除前4行 [英] How to delete the first 4 rows from multiple excel files using python pandas (Dataframes)
本文介绍了如何使用Python Pandas(Dataframes)从多个Excel文件中删除前4行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当前,我正在编写一个包含多个excel电子表格的程序。
Currently I am writing a program that combines multiple excel spreadsheets.
我想知道如何在合并每个电子表格之前删除前4行。下面是尝试删除前4行的特定语句,但出现错误。
I would like to know how to delete the first 4 rows from every spreadsheet before combining them. Below is the specific statement attempting to delete the first 4 rows but I am getting an error.
frames[0:] = [df.drop(df.index[[0,3]]) for df in frames[0:]]
下面是完整程序
import tkinter as tk
from tkinter import filedialog
from pathlib import Path
import pandas as pd
root = tk.Tk()
root.withdraw()
files = filedialog.askopenfilenames()
print("--------------")
print(files)
ExcelFileNames = [Path(x).name for x in files]
print("--------------")
print(type(ExcelFileNames))
print("--------------")
print(ExcelFileNames)
print("--------------")
print (ExcelFileNames[0])
print("--------------")
print("Number of files is:", len(ExcelFileNames))
# read them in
excels = [pd.ExcelFile(name) for name in ExcelFileNames]
# turn them into dataframes
frames = [x.parse(x.sheet_names[0], header=None,index_col=None) for x in excels]
frames[0:] = [df.drop(df.index[[0,3]]) for df in frames[0:]]
# delete the first row for all frames except the first
# i.e. remove the header row -- assumes it's the first
frames[1:] = [df[1:] for df in frames[1:]]
# concatenate them..
combined = pd.concat(frames)
# write it out
combined.to_excel("DNcombined.xlsx", header=False, index=False)
推荐答案
IIUC,
您可以添加 skiprows 转到您的参数,以跳过这些行,同时循环浏览列表。
you can add skiprows to your argument to skip these rows whilst looping over your list.
# read them in
excels = [pd.ExcelFile(name) for name in ExcelFileNames]
# turn them into dataframes
frames = [x.parse(x.sheet_names[0], header=None,index_col=None, skiprows=4) for x in excels]
这篇关于如何使用Python Pandas(Dataframes)从多个Excel文件中删除前4行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文