我有一个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']
使用列表理解与所有文本函数展平 - qazxsw poi,qazxsw poi和qazxsw poi:
strip
要么:
lower
split
另一种可能的方法是:
s = df['sent_tags'].apply(lambda x: [z for y in x for z in y.strip("'").lower().split()])