简体   繁体   English

使用Openpyxl在Python 3中一次删除几列

[英]Delete several columns at once in Python 3 using Openpyxl

After loading a file I am trying to delete 2 columns, but every time delete 1 column, the index of the next column I am trying to delete changes so I have to use index-1. 加载文件后,我尝试删除2列,但是每次删除1列时,我试图删除更改的下一列的索引,因此我必须使用index-1。 No problem if it's only 2 columns but if I have to be deleting several columns, how can I do it all at once? 没问题,如果只有2列,但是如果我必须删除几列,我该如何一次完成所有操作?

for file in files:
fileName = os.path.splitext(file)[0]
if fileName == 'Any file name':
    wb = load_workbook(file)
    sheet = wb.active
    # Delete the first 3 rows
    sheet.delete_rows(1, 3)
    # Delete Column G
    sheet.delete_cols(7)
    # Delete Column L
    sheet.delete_cols(12)
    workbook.save(file)

Should I use something different like numpy or work with everything using DataFrames? 我应该使用numpy之类的东西还是使用DataFrames处理所有事情?

If the dependency isn't too heavy I would recommend using pandas for this. 如果依赖性不太强,我建议为此使用熊猫。 Pandas has a read_excel function that uses Openpyxl under the hood and working with Pandas DataFrames is generally ergonomic and there are far more resources online (and answered stack overflow questions) for most issues you may run into. Pandas具有read_excel函数,该函数在read_excel使用Openpyxl,并且与Pandas DataFrames一起使用通常是符合人体工程学的,并且对于您可能会遇到的大多数问题,在线上的资源都很多(并回答了堆栈溢出问题)。

import pandas as pd

for file in files:
    fileName = os.path.splitext(file)[0]
    if fileName == 'Any file name':
        df = pd.read_excel(file)

        # Delete the first 3 rows
        df = df.drop([0, 1, 2], axis = 0)
        df = df.drop([7, 12])
        # Or if your excel file is labeled
        # df = df.drop(["G", "L"])
        df.write_excel(fileName)

You could delete the values starting with the rightmost index instead. 您可以改为从最右边的索引开始删除值。 For example to remove the 0th, 1st, and 2nd indices from a list: 例如,从列表中删除第0,第1和第2个索引:

>>> x = [0,1,2,3,4,5,6]
>>> del x[2]
>>> del x[1]
>>> del x[0]
>>> x
[3, 4, 5, 6]

Compare that result with your method, which deletes from left to right: 将结果与您的方法进行比较,该方法从左到右删除:

>>> x = [0,1,2,3,4,5,6]
>>> del x[0]
>>> del x[1]
>>> del x[2]
>>> x
[1, 3, 5, 6]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM