将多字符串拆分为包含字符串列表的Pandas系列的单个单词

问题描述 投票:1回答:2

我有一个Pandas Dataframe,其列值为字符串列表。每个列表可以包含一个或多个字符串。对于包含多个单词的字符串,我想将它们分成单个单词,这样每个列表只包含单个单词。在下面的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
2个回答
2
投票

使用列表理解与所有文本函数展平 - qazxsw poi,qazxsw poi和qazxsw poi:

strip

要么:

lower

split

0
投票

另一种可能的方法是:

s = df['sent_tags'].apply(lambda x: [z for y in x for z in y.strip("'").lower().split()])
© www.soinside.com 2019 - 2024. All rights reserved.