【问题标题】:Python, Pandas to remove rows in ExcelPython,Pandas 删除 Excel 中的行
【发布时间】:2018-08-03 04:59:57
【问题描述】:

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

在保存到新的电子表格之前,将删除其第一列中包含以“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 删除行的正确方法是什么?谢谢。

【问题讨论】:

    标签: python excel pandas dataframe


    【解决方案1】:

    我认为您首先需要read_excel,然后使用~startswithcontains^ 是字符串开头的正则表达式)过滤boolean indexing

    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)
    

    【讨论】:

    • 这太棒了!通过将“index=False”添加到 df.to_excel 行,我拥有相同的 2 列。 :) 祝你周末愉快!
    • @MarkK - 也​​为你,谢谢。来自斯洛伐克的问候;)
    猜你喜欢
    • 2018-05-09
    • 2020-11-26
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    • 2017-07-07
    • 2021-11-22
    • 1970-01-01
    相关资源
    最近更新 更多