Python to save needed rows in Excel contents -
i using windows 7 + python 2.76.
i trying save specific contents of xls files new files.
the original contents looks like:
what want save rows “uk” (2nd column) in new files.
what doing below:
old_file = open_workbook('c:\\1.xls',formatting_info=true) 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 = [] row in range(old_sheet.nrows): = old_sheet.cell(row,0).value b = old_sheet.cell(row,1).value c = old_sheet.cell(row,2).value if "uk" in b: contents.append(a) contents.append(b) contents.append(c) c, content in enumerate(contents): new_sheet.write(0, c, content) new_file.save('c:\\file_1.xls')
however puts results in 1 row. think it’s because put contents 1 list , write them 1 row.
but what’s right way put them? (as number of needed rows uncertain).
with pandas
:
import pandas pd orig_df = pd.read_excel(orig_excel_path, sheetname=sheetname) orig_df[orig_df['visited'] == 'uk'].to_excel(new_excel_path, sheet_name=new_sheetname)
breaking down:
orig_df['visited'] == 'uk'
returns list of true
or false
each row if visited
column 'uk'
. in case [false, true, false, true]
. passing list original dataframe give rows in indexes corresponding true
.
Comments
Post a Comment