【问题标题】:make new column based on presence of a word in another根据另一个单词的存在创建新列
【发布时间】:2019-11-27 16:15:49
【问题描述】:

我有

pd.DataFrame({'text':['fewfwePDFerglergl','htrZIPg','gemlHTML']})
    text
0   wePDFerglergl
1   htrZIPg
2   gemlHTML

10k 行长的列。每列包含 ['PDF','ZIP','HTML'] 之一。文本中每个条目的长度最大为 14 个字符。

我如何获得:

pd.DataFrame({'text':['wePDFerglergl','htrZIPg','gemlHTML'],'file_type':['pdf','zip','html']})
    text            file_type
0   wePDFerglergl   pdf
1   htrZIPg         zip
2   gemlHTML        html

我尝试df.text[0].find('ZIP') 单个条目,但不知道如何将它们拼接在一起以测试并返回列中每一行的正确值

有什么建议吗?

【问题讨论】:

    标签: pandas dataframe substring


    【解决方案1】:

    我们可以在这里使用str.extract 和正则表达式标志以区分大小写(?i)

    words =  ['pdf','zip','html']
    df['file_type'] = df['text'].str.extract(f'(?i)({"|".join(words)})')
    

    或者我们使用flags=re.IGNORECASE 参数:

    import re
    df['file_type'] = df['text'].str.extract(f'({"|".join(words)})', flags=re.IGNORECASE)
    

    输出

                    text file_type
    0  fewfwePDFerglergl       PDF
    1            htrZIPg       ZIP
    2           gemlHTML      HTML
    

    如果要将file_type 设为小写,请链接str.lower()

    df['file_type'] = df['text'].str.extract(f'(?i)({"|".join(words)})')[0].str.lower()
    
                    text file_type
    0  fewfwePDFerglergl       pdf
    1            htrZIPg       zip
    2           gemlHTML      html
    

    详情: 管道 (|) 是正则表达式中的 or 运算符。所以:

    "|".join(words)
    
    'pdf|zip|html'
    

    我们得到以下伪代码:

    从我们的字符串中提取“pdf”或“zip”或“html”

    【讨论】:

      【解决方案2】:

      您可以为此使用正则表达式:

      import re
      regex = re.compile(r'(PDF|ZIP|HTML)')
      

      这匹配任何所需的子字符串。为了在适当的情况下按顺序提取这些匹配,这里有一个单行:

      file_type = [re.search(regex, x).group().lower() for x in df['text']]
      

      这将返回以下列表:

      ['pdf', 'zip', 'html']
      

      然后添加列:

      df['file_type'] = file_type
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-02
        • 1970-01-01
        • 1970-01-01
        • 2023-03-25
        • 2022-10-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多