用于删除某些行的电子表格。
在保存到新电子表格之前,将删除其第一列中包含以“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 http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html,然后通过过滤boolean indexing http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing与反相掩模~
with startswith http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.startswith.html or contains http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html (^
是字符串开头的正则表达式):
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 http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html:
df.to_excel('C:\\result.xls', index=False)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)