首先,我在每个字符串末尾添加了一个空格,因为我们将在分组时合并句子。然后,我通过 st 列对分组后的句子进行了合并。
df['string']=df['string'] + ' '
dfx=df.groupby('st').agg({'st':'count','string':'sum'})
然后列出字符串表达式中的每个单词,计算它们的分布并获取前3个值。
from collections import Counter
mask=dfx['string'].apply(lambda x: list(dict(Counter(x.split()).most_common()[:3]).keys()))
print(mask)
'''
st string
us ['with', 'was', 'he']
us1 ['the', 'and', 'The']
us2 ['words', 'random', 'Random']
'''
最后,将这前三个单词添加为新列。
dfx[['top1_word','top2_word','top3_word']]=pd.DataFrame(mask.tolist(), index= mask.index)
dfx
st name_x_count top1_word top2_word top3_word
us 2 with was he
us1 2 the and The
us2 1 words random Random