【问题标题】:Scan columns for a keyword and extract all values in that column, if the keyword is found in that column如果在该列中找到关键字,则扫描列中的关键字并提取该列中的所有值
【发布时间】:2019-09-25 19:49:02
【问题描述】:

感谢您花时间在这里提供帮助,我真的很感激。

目前,我有多个 Excel 文件要循环浏览。

我只在 C:D 列中循环。如果该列具有关键字“缩写”,我想提取该列中的所有值。 这是因为我的关键字可能存在于 C 列或 D 列中。

我的列将如下所示:

导入我的 excel 文件后,这是我如何循环浏览要扫描的列:

wb1 = load_workbook(join(dict_folder, file), data_only = True)
ws = wb1.active

for rowofcellobj in ws["C":"D"]:
   for cellobj in rowofcellobj:
      if cellobj.value == "Abbreviation":
        # extract all words in that column but Idk how to execute this step or if my above steps are correct
        if cellobj.value is not None:
        data = re.findall(r"\b\w+_.*?\w+|[A-Z]*$\b", str(cellobj.value))
        #filtering out blank rows here:
         if data != [ ]:
            if data != [' ']:
                 #extracting words from square brackets in list:
                      fields = data[0]
                      print(fields)

我被困在我上面评论过的区域,说我不确定如何执行该步骤..

【问题讨论】:

  • 您是否尝试过使用pandas 读取excel 方法,而不是使用pandas 方法(寻找缩写列等)?
  • @EzerK 不,我没有尝试过使用 pandas,因为我对它的了解不多,而且我已经开始使用 openpyxl。这对熊猫来说可行吗?因为我担心熊猫无法读取列,除非它是工作表的第一行
  • 这是 pandas 的经典任务(不是你说这是唯一的方法)看看 pandas 阅读 excel 文档

标签: python excel python-3.x


【解决方案1】:

Pandas 解决方案,灵感来自 (link)

示例文件:

import pandas as pd 
import numpy as np

df = pd.read_excel('tst.xlsx', usecols="C:D")
df = df.fillna('') 

for row in range(df.shape[0]): 
       for col in range(df.shape[1]):
           if df.iat[row,col] == 'Abbreviation':
             row_start = row
             col_required = col
             break

df = df.loc[row_start+1:, df.columns[col_required]]
df.replace(['','\s+'], np.nan, inplace=True, regex=True)
df.dropna(inplace=True)

print(df)

结果:

9      sfsdfd
10    fgfg_ff
12        dfs
13        ddd
15      dd_hh

【讨论】:

  • 您好弗拉迪斯拉夫,感谢您的回复!我一直在尝试实现您的代码。但我什至无法到达那一步,因为当我运行时:dict_folder = "C:/Users/xxx/Documents/Docs did/Requests"for file in os.listdir(dict_folder):if re.search(r'\.xlsx$', file):df = pd.read_excel((file), usecols = "C:D")
【解决方案2】:

问题:扫描列中的关键字并提取该列中的所有值

  • 定义起始行,这里1

    min_row = 1
    min_col = None
    
  • 循环所有行,从 min_row 开始并递增:

    for row in ws.iter_rows(min_row=min_row, values_only=True):
        min_row += 1
    
  • try 在此row 中查找关键字,如果找到则break
    由于index0-based+1 得到列索引1-based

        try:
            min_col = row.index('Abbreviation') + 1
            break
        except:
            continue
    
  • 如果找到,循环所有后续行,直到最后。

    注意:您还没有定义结束条件

    if min_col is not None:
        for value in map(lambda x: x[0], 
                         sheet1.iter_rows(min_row=min_row, 
                                          min_col=min_col,                                  
                                          max_col=min_col,
                                          values_only=True)):
            print(value)
    

【讨论】:

  • 嗨!这似乎工作,但它仍然打印出行 None....
猜你喜欢
  • 1970-01-01
  • 2023-04-09
  • 2020-12-11
  • 1970-01-01
  • 2022-07-12
  • 1970-01-01
  • 2014-06-30
  • 1970-01-01
  • 2021-12-23
相关资源
最近更新 更多