Skip to main content
 首页 » 编程设计

Python、Pandas 删除 Excel 中的行

2025年01月19日7webabcd

用于删除某些行的电子表格。

在保存到新电子表格之前,其第一列中包含以“36”开头的值的所有行都将被删除。

我使用这些代码(之后需要在 Excel 中拆分列)。该示例如下所示:

import xlwt 
from xlrd import open_workbook 
 
old_file = open_workbook('C:\\original.xlsx') 
old_sheet = old_file.sheet_by_index(0) 
 
new_file = xlwt.Workbook(encoding='utf-8', style_compression = 0) 
new_sheet = new_file.add_sheet('Sheet1', cell_overwrite_ok = True) 
 
contents = [] 
 
for row in range(old_sheet.nrows): 
    a = str(old_sheet.cell(row,0).value) 
    b = str(old_sheet.cell(row,1).value) 
 
    if not a.startswith("36"): 
        contents.append(a + "," + b) 
 
for c, content in enumerate(contents): 
    new_sheet.write(c, 0, content) 
 
new_file.save('C:\\result.xls') 

这还不够,所以我想学习 Pandas 的方式。

我尝试了类似 df.drop(["3649"]) 的方法,但它不起作用。

删除行的正确 Pandas 方法是什么?谢谢。

请您参考如下方法:

我想你首先需要read_excel ,然后按 boolean indexing 过滤通过 ~ 和 startswith 反转掩码或 contains (^ 是字符串开头的正则表达式):

df = pd.read_excel('C:\\original.xlsx') 
 
df = df[~df['Model'].astype(str).str.startswith('36')] 

备选方案:

df = df[~df['Model'].astype(str).str.contains('^36')] 
 
print (df) 
   Model Country 
0   1021  France 
1   9644   India 
2   9656   India 
4   9687   China 
6   9630   Spain 
7   9666  Brasil 

最后to_excel :

df.to_excel('C:\\result.xls', index=False)