【问题标题】:Split multi-word strings into individual words for Pandas series containing list of strings将多词字符串拆分为包含字符串列表的 Pandas 系列的单个单词
【发布时间】:2019-03-18 11:35:44
【问题描述】:

我有一个 Pandas 数据框,它的列值作为字符串列表。每个列表可能有一个或多个字符串。对于包含多个单词的字符串,我想将它们拆分为单个单词,以便每个列表仅包含单个单词。在以下 Dataframe 中,只有 sent_tags 列具有包含可变长度字符串的列表。

数据帧

import pandas as pd    
pd.set_option('display.max_colwidth', -1)
df = pd.DataFrame({"fruit_tags": [["'apples'", "'oranges'", "'pears'"], ["'melons'", "'peaches'", "'kiwis'"]], "sent_tags":[["'apples'", "'sweeter than oranges'", "'pears sweeter than apples'"], ["'melons'", "'sweeter than peaches'", "'kiwis sweeter than melons'"]]})
print(df)  

    fruit_tags                        sent_tags
0   ['apples', 'oranges', 'pears']  ['apples', 'sweeter than oranges', 'pears sweeter than apples']
1   ['melons', 'peaches', 'kiwis']  ['melons', 'sweeter than peaches', 'kiwis sweeter than melons']

我的尝试

我决定使用 NLTK 库中的 word_tokenize 将这些字符串分解为单个单词。我确实得到了列表中特定选择的标记词,但不能将它们组合到每一行的每个列表中:

from nltk.tokenize import word_tokenize
df['sent_tags'].str[1].str.strip("'").apply(lambda x:word_tokenize(x.lower()))
#Output
0    [sweeter, than, oranges]
1    [sweeter, than, peaches]
Name: sent_tags, dtype: object

期望的结果

    fruit_tags                        sent_tags
0   ['apples', 'oranges', 'pears']  ['apples', 'sweeter', 'than', 'oranges', 'pears', 'sweeter', 'than', 'apples']
1   ['melons', 'peaches', 'kiwis']  ['melons', 'sweeter', 'than', 'peaches', 'kiwis', 'sweeter', 'than', 'melons']

【问题讨论】:

    标签: python python-3.x pandas


    【解决方案1】:

    对所有文本函数使用带有展平的列表理解 - striplowersplit

    s = df['sent_tags'].apply(lambda x: [z for y in x for z in y.strip("'").lower().split()])
    

    或者:

    s = [[z for y in x for z in y.strip("'").lower().split()] for x in df['sent_tags']]
    

    df['sent_tags'] = s
    
    print(df) 
                           fruit_tags  \
    0  ['apples', 'oranges', 'pears']   
    1  ['melons', 'peaches', 'kiwis']   
    
                                                            sent_tags  
    0  [apples, sweeter, than, oranges, pears, sweeter, than, apples]  
    1  [melons, sweeter, than, peaches, kiwis, sweeter, than, melons]  
    

    【讨论】:

    • 太棒了!非常感谢!
    【解决方案2】:

    另一种可能的方法是:

    df['sent_tags'].apply(lambda x: [item for elem in [y.split() for y in x] for item in elem])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-16
      • 2011-11-03
      • 2019-03-12
      • 2022-01-18
      • 1970-01-01
      • 2023-01-22
      • 2022-07-06
      • 2018-04-06
      相关资源
      最近更新 更多