Python在Excel内容中保存所需的行

标签 python excel python-2.7

我使用的是 Windows 7 + Python 2.76。

我正在尝试将 xls 文件的特定内容保存到新文件中。

原始内容如下:

enter image description here

我想要做的是将所有带有“UK”的行(第二列)保存在新文件中。

我正在做的事情如下:

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 = []

for row in range(old_sheet.nrows):
    a = 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)

for c, content in enumerate(contents):
    new_sheet.write(0, c, content)


new_file.save('C:\\file_1.xls')

但是它只将所有结果放在 1 行中。我认为这是因为我将所有内容放入 1 个列表并将它们写入 1 行。

但是放置它们的正确方法是什么? (因为所需的行数不确定)。

最佳答案

Pandas :

import pandas as 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)

分解:

orig_df['Visited'] == 'UK' 如果 为每行返回 TrueFalse 列表访问的列是'UK'。在本例中为[False, True, False, True]。将此列表传递回原始数据帧将只为我们提供索引中与 True 对应的行。

关于Python在Excel内容中保存所需的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32042404/

相关文章:

python - 字节数组和列表的区别

python - 如何在 python 中从附近主机检索 MAC 地址?

python - 按 dtype 和列名选择 Pandas 列

python - 将元素列表映射到 pandas 中的元素类别?

excel - 如何将分类值转换为 Excel 中的列?

vba - 如何在VBA中添加两个矩阵?

python-2.7 - 使用 ORB 图像特征匹配时 OpenCV python 错误

python - 在没有实例的类对象上设置魔术方法?

python - Keras 值错误 : input 0 is incompatible with layer flatten_11

c# - APP 洞察模式 机器学习