如何在使用 python 解析来自 excel 的数据时 Delete/Ignore 某些行

How Do I Delete/Ignore some rows while parsing data from excel using python

最近我正在尝试使用 python 解析来自 Excel sheet 的数据,我成功地解析了它,但我不需要 excel sheet。那么该怎么做(可能正在使用循环)。这是我为解析 excel sheet:

而编写的代码
import xlrd



book = xlrd.open_workbook("Excel.xlsx")

sheet = book.sheet_by_index(0)
firstcol = sheet.col_values(0)
data = [[sheet.cell_value(r, c) for c in range(sheet.ncols)] for r in 
        range(sheet.nrows)]


ele=''
year=[]

for j in range(len(data)):
    if j==1:
        year=data[j]
    if j>2:
        ele=data[j][0]

        for i in range(1, len(data[j])):
            if ele != "":
                if data[j][i] != "":
                    if year[i] !="":
                        print([ele, data[j][i], year[i]])

所有行都以我想要的列表格式进行解析,但我不想要来自 excel 文件的某些行**(如总年龄、总 ID、总结果)**,所以我如何用相同的代码实现它或建议一些其他有效的方法(可能是 pandas)来减少代码或任何强大的方法。 Excel 文件引用: Click to see Excel.xlsx

提前致谢......

如果我没理解错的话,你可以做的更简单。您有一些要排除的行列表:

rows_to_exclude = ['Total age', 'Total IDS', 'Total Result']

您可以在不使用 xlrd 的情况下使用 pd.read_excel 读取数据帧(如果是第一个 sheet,则无需指定 sheet 索引,这是默认读取的)。然后您可以删除具有缺失值的行,并删除其索引在您的排除行标签列表中的所有行:

df = pd.read_excel('Excel.xlsx')
df = df.dropna().drop(rows_to_exclude)