首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Openpyxl,Pandas或两者兼而有之

问Openpyxl,Pandas或两者兼而有之
EN

Stack Overflow用户
提问于 2021-11-20 15:30:47
回答 1查看 3.8K关注 0票数 1

我正在尝试处理一个excel文件,以便以后可以将每一行和每一列用于特定的操作。

我的问题如下:

  • 使用Openpyxl使我更容易加载文件并能够遍历行。
代码语言:javascript
复制
    #reading the excel file
    path = r'Datasets/Chapter 1/Table B1.1.xlsx'
    wb = load_workbook(path) #loading the excel table
    ws = wb.active #grab the active worksheet
    
    #Setting the doc Header
    for h in ws.iter_rows(max_row = 1, values_only = True): #getting the first row (Headers) in the table
        header = list(h)
    
    for sh in ws.iter_rows(min_row = 1 ,max_row = 2, values_only = True):
        sub_header = list(sh)
    
    #removing all of the none Values
    header = list(filter(None, header))
    sub_header = list(filter(None, sub_header))
    #creating a list of all the rows in the excel file
    row_list = []
    
    for row in ws.iter_rows(min_row=3): #Iteration over every single row starting from the third row since first two are the headers
        row = [cell.value for cell in row] #Creating a list from each row
        row = list(filter(None, row)) #removing the none values from each row
        row_list.append(row) #creating a list of all rows (starting from the 3d one)

    colm = []
    for col in ws.iter_cols(min_row=3,min_col = 1): #Iteration over every single row starting from the third row since first two are the headers
        col = [cell.value for cell in col] #Creating a list from each row
        col = list(filter(None, col)) #removing the none values from each row
        colm.append(col) #creating a list of all rows (starting from the 3d one)

但同时(就我在文档中读到的内容而言),我无法可视化它,也无法对行或列执行直接操作。

  • 虽然使用熊猫可以更有效地对行和列进行直接操作,但我已经看到,即使使用df.iloc[2:]进行迭代以获得列表中的行,也不建议进行迭代--它不会给出相同的结果(将每一行保存在特定的列表中,因为标题将始终存在)。但是,与Openpyxl不同的是,使用像df[col1]-df[col2]这样的使用列名的方法对列进行直接操作要容易得多,这是我需要做的事情。(因为仅仅将所有列值放入列表中都不会对我起作用)

因此,我的问题是,是否有一种解决方案可以只使用其中一种来完成我想做的事情,或者如果使用这两种方法都没有那么糟糕,请记住,我必须加载两次excel文件。

“事先谢谢!”

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-23 07:45:01

使用openpyxl读取excel文件,然后将行加载到熊猫中是没有问题的:

代码语言:javascript
复制
pandas.DataFrame(row_list, columns=header)

您说得对,使用索引迭代DataFrame非常慢,但是您还有其他选项:apply()、iterrows()、itertuples()

链接:熊猫DataFrame中不同的行迭代方法

我还想指出的是,您的代码可能没有做您想做的事情。

  1. list(filter(None, header))不仅没有过滤,而且过滤所有虚假的值,比如0或""。
  2. 这样的过滤转移了列。例如,您有一个行[1, None, 3]和列['a', 'b', 'c']。通过过滤None,您将得到[1, 3],它将与'a'和'b'列相关联。
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70047335

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档