【问题标题】:List comparisons for pandas column of lists列表的 pandas 列的列表比较
【发布时间】:2020-08-07 13:05:15
【问题描述】:

我有一个代表库的 pandas 数据框。这些列代表元数据,例如作者、标题、年份和文本。文本列包含带有书籍文本的列表,其中每个列表元素代表书中的一个句子(见下文)

     Author  Title   Text
0    Smith   ABC    ["This is the first sentence", "This is the second sentence"]
1    Green   XYZ    ["Also a sentence", "And the second sentence"]

我想对句子进行一些 NLP 分析。对于个别示例,我将使用列表比较,但是如何以最 Pythonic 的方式对列使用列表比较?

我想做的是例如使用包含单词 "the" 的句子列表创建一个新列,例如在此示例中:How to test if a string contains one of the substrings in a list, in pandas?

但是,他们使用带有字符串列而不是列表列的数据框。

【问题讨论】:

    标签: python regex pandas list


    【解决方案1】:

    您可以使用DataFrame.apply 和正则表达式来做到这一点。

    import re
    import pandas as pd
    
    data = {
        'Author': ['Smith', 'Green'],
        'Title' : ['ABC', 'XYZ'],
        'Text' : [
            ["This is the first sentence", "This is the second sentence"],
            ["Also a sentence", "And the second sentence"]
        ]
    }
    
    df = pd.DataFrame(data)
    
    tokens = [
        'first',
        'second',
        'th'
    ]
    
    def find_token(text_list, re_pattern):
        result = [
            text
            for text in text_list
            if re.search(re_pattern, text.lower())
        ]
        if result:
            return result
        return
    
    for token in tokens:
        re_pattern = re.compile(fr'(^|\s){token}($|\s)')
        df[token] = df['Text'].apply(lambda x: find_token(x, re_pattern))
    

    重新匹配令牌word
    所以必须有空格或句子的开头/结尾。
    re.compile(r'(^|\s)') 表示空格或开头。
    re.compile(r'($|\s)') 表示空格或结尾。

    如果您使用 'th' 作为标记,结果将是 None

    使用tokens作为['first', 'second', 'th'],结果如下。

      Author Title                                               Text  \
    0  Smith   ABC  [This is the first sentence, This is the secon...   
    1  Green   XYZ         [Also a sentence, And the second sentence]   
    
                              first                         second    th  
    0  [This is the first sentence]  [This is the second sentence]  None  
    1                          None      [And the second sentence]  None  
    

    【讨论】:

      猜你喜欢
      • 2018-11-18
      • 2020-12-02
      • 1970-01-01
      • 2023-01-12
      • 2022-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-12
      相关资源
      最近更新 更多